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.

MMR
  • 2,869
  • 13
  • 56
  • 110
  • 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`](https://angular.io/docs/ts/latest/api/http/index/Response-class.html) instead. You can always `Observable.throw` from the service and catch that in the later code that consumes the service. – Neil Lunn May 16 '17 at 09:55
  • Possible duplicate of [RxJs catch error and continue](http://stackoverflow.com/questions/38649652/rxjs-catch-error-and-continue) – Neil Lunn May 16 '17 at 10:02

3 Answers3

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

eko
  • 39,722
  • 10
  • 72
  • 98
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.

ulubeyn
  • 2,761
  • 1
  • 18
  • 29
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)}); 
Milad
  • 27,506
  • 11
  • 76
  • 85