Angular文档说:
响应正文不会返回您可能需要的所有数据 . 有时,服务器返回特殊 Headers 或状态代码以指示某些条件,并且检查这些条件是必要的 . 要做到这一点,你可以告诉HttpClient你想要完整的响应,而不仅仅是带有observe选项的body:
http
.get<MyJsonData>('/data.json', {observe: 'response'})
.subscribe(resp => {
// Here, resp is of type HttpResponse<MyJsonData>.
// You can inspect its headers:
console.log(resp.headers.get('X-Custom-Header'));
// And access the body directly, which is typed as MyJsonData as requested.
console.log(resp.body.someField);
});
但是当我尝试这个时,我得到一个编译时错误(尽管没有运行时错误,按预期工作):
错误TS2345:类型'{headers:HttpHeaders;观察:字符串; ''不能赋值给'{headers?:HttpHeaders |'类型的参数{[header:string]:string |串[]; };观察?:“身体”; params?:Ht ......' . property '观察'的类型是不相容的 . 类型'string'不能分配给''body'' .
为什么?我用 "@angular/http": "^5.1.0"
这是我的代码版本:
login(credentials: Credentials): Observable<any> {
const options = {
headers: new HttpHeaders({'Content-Type': 'application/json'}),
observe: 'response'
};
return this.httpClient.post<any>(`${environment.USER_SERVICE_BASE_URL}`,
{'username': credentials.username, 'password': credentials.password}, options)
.map((res) => ...
2 回答
你必须内联选项 . 请参阅2017年8月9日
alxhub
的github ticket #18586 .我解决这个问题的方法是,没有内联选项(可能导致代码不干净)是为请求选项创建一个接口 . 代码如下所示:
然后这样使用:
更改原始帖子使用
lettable
或pipeable
(无论当前名称是什么)运营商