2

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.

1
  • The code below "I try to auth" is in the apiUser.login() {...}? Commented Nov 28, 2016 at 16:10

1 Answer 1

1

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),
    );
Sign up to request clarification or add additional context in comments.

1 Comment

You're THE man ! I tried to do this since 3 hours... And here u come... Ty Mate !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.