这一切都取决于 RxJs 的版本。 Angular 6 随 RxJs 6 一起提供 - 这意味着 map()/catch() 方法不再有效。
相反,您必须使用 pipeline + map()/catchError() ,如下所示:
在 Angular 6 / RxJs 6 之前 - 经典的 Http 使用:
return this.http.get(url, {headers: this.headers}).map(
(response: Response) => {
const data : SomeType = response.json() as SomeType;
// Does something on data.data
// return the modified data:
return data.data; // assuming SomeType has a data properties. Following OP post
}
).catch(
(error: Response) => {
throwError(error); // From 'rxjs'
}
);
应该改成这样:
Angular 6 / RxJs 6 - HttpClient 迁移后:
return this.http.get<SomeType>(url, {headers: this.headers})
.pipe(
map( response => { // NOTE: response is of type SomeType
// Does something on response.data
// modify the response.data as you see fit.
// return the modified data:
return response; // kind of useless
}),
catchError( error => {
return throwError(error); // From 'rxjs'
})
); // end of pipe
在管道中,map() 将获取响应对象(已从 JSON 解析),如果 HTTP 失败,catchError() 将获取第一个错误。
另请注意,您的 Headers 也必须是 HttpHeaders 对象。
阅读 RxJs 6 中的管道、映射和 catchError