我正在升级到Angular到版本5,之前我正在使用@ angular / http,现在我需要更新到@ angular / common / http并使用
HttpClient
我已经在服务中(而不是在组件中)发出http请求,这使得它们易于重用
这就是我已经拥有的(来自已弃用的http)
return this.http.get(url,{headers: this.headers}).map( (response: Response) => { const data = response.json(); // Does something on data.data // return the modified data: return data.data; } ).catch( (error: Response) => { return Observable.throw(error); } );
现在从我从新的HttpClient中学到的东西,就像我无法修改响应并将其提供给订阅它的组件方法.
我应该如何修改对HTTP请求的响应并在从Observable返回之前轻松访问它?
解决方法
这一切都取决于RxJ的版本. Angular 6附带RxJs 6 – 这意味着map()/ catch()方法不再有效.
相反,您必须使用pipe 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) => { return Observable.throw(error); } );
应改为:
在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 Observable.throw(error); }) ); // end of pipe
在管道中,map()将获取响应对象(已经从Json解析),如果http失败,catchError()将获取第一个错误.
另外,请注意您的Headers也需要是HttpHeaders对象.
读取RxJs 6中的pipe,map和catchError
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。