【发布时间】:2016-03-18 06:00:40
【问题描述】:
我正在 angular2 中进行一些 REST 调用(使用 HTTP 请求)。取决于条件请求的类型为 GET、POST、PUT、DELETE。 一切对我来说都很好,我正在使用以下方法使用单独的服务文件和类(组件类)文件发出请求。
* service.ts
PostRequest(url,data){
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
body: JSON.stringify(data),
headers: this.headers
})
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if(res.status == 201){
return [{ status: res.status, json: res.json }]
}
else if(res.status != 201){
return [{ status: res.status, json: null }]
}
}
// i want to handle error here but how i don't know
});
}
- component_class.ts
this.base_path_service.PostRequest(url_postSection, data)
.subscribe(res=> {
if (res[0].status == 201) { //some stuff here..... }
});
现在来提问,我的问题是
- 如何处理 http 中发生的错误,
我知道
next,error,oncomplete订阅方法,但是否可以在映射可观察 i.r 时处理错误 返回 this.http.request(新请求(this.requestoptions)) .map( //是否可以在订阅时在这里处理错误)-
我想通知用户取决于状态代码(201,200,204 等...),所以我想编写一次代码,即在 .map 时而不是 订阅的时候再写代码
如果有其他方法适用于 HTTP 时的错误处理,请将其作为示例发布。
【问题讨论】: