1

I ave a server call like below

In success case,

STATUS---200

{error_code: 0, status: "success", results: [,…], message: "Album successfully found."}

In failure case, STATUS---401

 Login credentials are incorrect.

I am handling the code as,

 this.http.post(this.serverUrl+'login',loginForm.value,{headers: headers})
        .subscribe(response => {
            if (response.json().error_code === 0) {
               console.log('success'); 
            } else {
               console.log('fail'); 
            }
        }) 
  }

But here its an error (401-status).So it is not coming to the else case.Can anyone suggest help to handle or catch this error.thanks.

2
  • That's all and nice if your server returned a "nice" JSON response about the error, but in case it does not then I would be looking at the .status property of the Response instead. You can always Observable.throw from the service and catch that in the later code that consumes the service. Commented May 16, 2017 at 9:55
  • Possible duplicate of RxJs catch error and continue Commented May 16, 2017 at 10:02

3 Answers 3

1

Subscribe has an error callback:

 this.http.post(this.serverUrl+'login',loginForm.value,{headers: headers})
        .subscribe(
        (response) => {
            if (response.json().error_code === 0) {
               console.log('success'); 
            } else {
               console.log('fail'); 
            }
        },
        (error)=>{
            console.log(error);
        }
     ) 
  }

Example in docs: https://angular.io/docs/ts/latest/guide/server-communication.html#!#the-herolistcomponent-class

Sign up to request clarification or add additional context in comments.

Comments

1

Subscribe method takes 3 parameters, first one is invoked when successfull response is received, second one is called when error response is received, and third one is called when it is completed. You should try this one;

this.http.post(yourParameters).subscribe(response => {
     console.log('success');
}, error => {
     console.log('fail')
});

I also recommend you to take a look at angular tutorial and Rxjs Subscribe.

Comments

1

You can use .catch as well :

this.http.post(this.serverUrl+'login',loginForm.value,{headers: headers})
        .subscribe(response => {
            if (response.json().error_code === 0) {
               console.log('success'); 
            } else {
               console.log('fail'); 
            }
        }).catch((err)=>{console.log(err)}); 

Comments

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.