作者:KING树林_944 | 来源:互联网 | 2023-01-04 20:25
我正在尝试将post api的头设置为application.json
let options: { headers?: {'Content-Type':'application/json'} }
但没有设定.
1> Luca Ritossa..:
要使用新的HttpClient类定义内容类型,您需要:
从@angular/common/http
(并且@angular/http
当前未标记为已弃用)
import { HttpClient, HttpHeaders } from '@angular/common/http';
HttpClient
在构造函数上注入:
constructor(private http: HttpClient) { }
定义私有字段headers
以定义所需的内容类型,并 options
准备将在调用中使用的对象:
private optiOns= { headers: new HttpHeaders().set('Content-Type', 'application/json') };
在您的方法中使用它:
this.http.post('your target url', yourBodyObject, this.options)
其中'your target url'
和yourBodyObject
仅用作示例,需要替换为您的实际数据.
2> Drenai..:
Angular文档中有一节内容 - 可能最近添加了:
import { HttpHeaders } from '@angular/common/http';
const httpOptiOns= {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
当我尝试使用上述格式向httpOptions添加响应类型时,TypeScript给了我警告,所以我成功使用了以下内容:
let headers = new HttpHeaders({
'Content-Type': 'application/text'
});
return this.http.get(url, { responseType: 'text', headers })
文档链接