user3402182 user3402182 - 8 days ago 5
HTTP Question

angular2 wait for error http response

I have a problem with angular2 http response.

I want to catch the error in my component.

How does my app work.
In my Component, I Call a function in a personal service :

var response = this.apiUser.login(username, password);
alert(response);


In my Service, I try to auth :

this.http.post(this.httpApiAdress + '/' + this.httpUserAutenticate, body, { headers: contentHeaders })
.subscribe(
response => {
localStorage.setItem('id_token', response.json().token);
this.router.navigate(['home']);
},
error => {
return error.json();
},
() => { }
);


When the auth is ok, all work fine. But when the Auth fail, i can't catch the response in my Component.
(Its undefinied because the alert is executed before the http call...)

Can u help me please !!! (It was working when all the code was only in my Component, but I wanted to slip my code...)

Ty.

Answer

Return the observable by using map() instead of subscribe()

return this.http.post(this.httpApiAdress + '/' + this.httpUserAutenticate, body, { headers: contentHeaders })
.map(
    response => {
        localStorage.setItem('id_token', response.json().token);
        this.router.navigate(['home']);
    },
);

and then use subscribe where you want to execute code when the response or error arrives

    var response = this.apiUser.login(username, password)
    .subscribe(
        response => alert(response), 
        error => alert(error),
    );