如何在Angular中实现最简单的http post请求?

如何在Angular中实现最简单的http post请求?,angular,httpclient,Angular,Httpclient,为了让一个简单的http post正常工作,我的代码如下: var config = { headers : { 'Content-Type': 'application/json' } } var data = { "gender":"M" }; this.http.post<any>("http://localhost:8080/rest/endpoint", JSON.stringify

为了让一个简单的http post正常工作,我的代码如下:

var config = {
      headers : {
          'Content-Type': 'application/json'
      }
    }

    var data = {
      "gender":"M"
    };

    this.http.post<any>("http://localhost:8080/rest/endpoint", JSON.stringify(data), config)
    .subscribe(
        (val) => {
            console.log("POST call successful value returned in body", 
                        val);
        },
        response => {
            console.log("POST call in error", response);
        },
        () => {
            console.log("The POST observable is now completed.");
        }
    );
  }

实际上,最佳实践是分别维护服务和组件。
如果使用angular cli,您可以通过ng g service serviceName生成新服务
将服务添加/包含到providers数组中的appmodule(根模块)以使其全局可访问。您也可以通过将服务包含在特定的component.ts文件中使其成为本地服务。
我将为你提供基本的前景/工作经验。 在service.ts中导入必要的模块。


如果您使用的是
HttpClient
,则无需对数据进行字符串化,直接传入
data
(作为对象)。我确实直接尝试了该对象,但没有进行字符串化,结果相同。boreq,我认为CORS不会有问题,因为angular和API都运行localli,不是吗?我的意图是在同一个域的不同子域中部署angular和API,这行得通吗?允许CORS后就行了。我已经按照建议将调用分离到一个服务中,但这没有任何区别,无论如何,谢谢。我可以看到它现在组织得更好了。您是否在根模块中导入了httpclientmodule?是的,它已导入,我开始怀疑这确实是一个CORS问题,正如boreq在问题中的评论中所链接的那样,但还不确定。您是否在后端设置了allowedCorsOrigin=“*”?目前正在尝试配置它,但事实并非如此,但一开始错误看起来不像CORS问题。
**General**
Request URL: http://localhost:8080/rest/endpoint
Request Method: OPTIONS
Status Code: 200 
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
**Response Headers:**
Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS
Content-Length: 0
Date: Mon, 22 Apr 2019 11:18:51 GMT
**Request Headers:**
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:8080
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Mobile Safari/537.36
import { Injectable } from '@angular/core'; 
import { HttpClient, HttpParams, HttpErrorResponse } from "@angular/common/http";
import { Observable } from "rxjs";
@Injectable({
  providedIn: 'root'
})
export class serviceName {
  private url = `http://localhost:8080/rest/endpoint`
  constructor(private http: HttpClient) { }

  //method 
  public newGender(data): Observable<any> {
    const params = new HttpParams()
      .set('gender', data.gender)
    return this.http.post(`${this.url}`, params)
  }
constructor(service:serviceName){}
//subscribe to service now
//method
public methodName=()=>{
   let data = {
      "gender":"M"
    };
this.service.newGender(data).susbcribe(
response=>{
//your response
})
} //end method (call this method if needed)