Http请求(REST API)angular2

时间:2016-03-18 06:00:41

标签: rest http service angular

我在angular2中进行一些REST调用(使用HTTP请求)。依赖于条件请求的类型为GET,POST,PUT,DELETE。 一切正常,我使用下面的方法使用seprate服务文件和类(组件类)文件发出请求。

* 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时处理错误      return this.http.request(new Request(this.requestoptions))       .map(//可以在订阅时处理错误)

  • 我想通知用户取决于状态代码(201,200,204等...),所以我想编写一次代码,即.map而不是   在订阅时再次编写代码agagin

    如果任何其他方法有利于错误处理,而HTTP请以示例的方式将其作为答案发布。

1 个答案:

答案 0 :(得分:3)

您可以利用catch运算符来处理错误:

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 }]
            }
        }
    }).catch(error) => {
      // Do something
      // Observable.throw(new Error('some error');
    }); 
}

实际上,当发生错误时,将不会调用注册的回调而不是地图运算符。