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



正在努力让一个简单的http帖子工作,这是我的代码:

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.");
}
);
}

此请求是通过单击按钮调用的,执行时,我可以在 Chrome 网络选项卡中看到已执行选项 http 请求,该请求返回了 GET、HEAD、POST、PUT、DELETE、OPTIONS 然后执行了 POST,但它似乎没有发送我打算发送的正文数据, 以下是我在"网络"选项卡中看到的内容:

**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

在 Angular 中,最佳实践是分别维护服务和组件。
如果使用角度 cli,您可以通过ng g 服务服务名称将服务
添加/包含服务添加到提供程序数组中的 appmodule(根模块)以使其全局可访问来生成新服务。您也可以通过将服务包含在特定的 component.ts 文件中来使服务本地化。
我会为您提供基本的观点/工作。 在 service.ts 中导入必要的模块。

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)

最新更新