Angular文档说:
响应正文不会返回您可能需要的所有数据。有时,服务器返回特殊的标头或状态代码以指示某些条件,因此可能有必要进行检查。为此,您可以告诉HttpClient您想要完整的响应,而不仅仅是带有watch选项的正文:
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]:字符串| 串[]; }; 观察?:“身体”;参数?:Ht ...'。属性“观察”的类型不兼容。类型“字符串”不可分配给类型““ 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) => ...
您必须内联选项。参见github票证#18586,alxhub
于2017年8月9日进入。
为了为get()选择正确的返回类型,Typescript需要能够静态地推断观察值和responseType值。如果传入类型错误的选项对象,则无法推断正确的返回类型。
login(credentials: Credentials): Observable<any> {
return this.httpClient.post<any>(`${environment.USER_SERVICE_BASE_URL}`,
{'username': credentials.username, 'password': credentials.password}, {
headers: new HttpHeaders({'Content-Type': 'application/json'}),
observe: 'response'
})
.map((res) => ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句