Reputation: 493
This is regarding handling server response in angular2
As i understand,
1. server response code 200, 201 etc will make success response
2. while server response 400, 401, 500 etc will make error response
3. if response is success, then it will goto map function, from there we can return the data or modify it.
4. if response is error, then it will go to catch function, from there we will can return observable or throw the observable.
My question is if server returned error response code along with error data, then how to capture that data.
i.e suppose i am sending below data from server
success response
status: 200
msg: "successfully loggedin"
error response
status: 400
msg: "userid and password is wrong"
Here i am able to get or handle success data but not the error data,because in catch function, only error object is getting passed and that error object only contain response code from server, not the response data
return this.http.get('/login')
.map( (res: Response) => res.json().data )
.catch( (error: any) => {
return Observable.throw( new Error("error occured"+error.status));
})
Upvotes: 6
Views: 9756
Reputation: 16917
You don't have to .catch()
it!
If your server sends the correct message, just subscribe that Observable!
yourLoginService.LogInFunction().subscribe(
successData => console.log(successData),
errData => console.log(errData)
);
Upvotes: 2
Reputation: 493
Update:
don't put return in map and catch function.
Below is updated code
return this.http.get('/login')
.map( ( successRes: Response) => {
res.json().data
)}
.catch( ( errorRes: Response ) => {
Observable.throw( errorRes.json().data );
})
Original:
Actually solution was very simple, response data itself is attached to first argument, its just like normal response as in the case of success response.
Just needed to add json() call to response error object to convert the json to js object, something like this.
return this.http.get('/login')
.map( ( successRes: Response) => {
return res.json().data
)}
.catch( ( errorRes: Response ) => {
return Observable.throw( errorRes.json().data );
})
Upvotes: 4