Reputation: 86730
I am making some REST call (using HTTP request) in angular2.As depend on condition requests are of type GET,POST,PUT,DELETE. Everything works fine for me i am using the below method to make request using seprate service file and class (component class) file.
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
});
}
this.base_path_service.PostRequest(url_postSection, data)
.subscribe(res=> {
if (res[0].status == 201) { //some stuff here..... }
});
Now come to question, my Question is
i know next,error,oncomplete
methods of subscribe but is it possible to handle the error at the time of mapping observable i.r
return this.http.request(new Request(this.requestoptions))
.map( //is it possible to handle error here instead at the time of subscribe)
i want to get notify to user depends on status code(201,200,204 etc...), so i want to write code once i.e at the time of .map instead of writing code agagin and again at the time of subscribe
if any another approach is good for error handling while HTTP please post it as answer with example.
Upvotes: 1
Views: 1639
Reputation: 202138
You can leverage the catch operator to handle errors:
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');
});
}
In fact when an error occurs, the registered callback un the map operator won't be called.
Upvotes: 3