How to catch HTTP errors using angular2?

Is there an API similar to angular 1.x Interceptor API?

I want to be able to add interceptors when starting an application that will

  • displays login dialog when status code 401 returned
  • shows a general error message when status code 5xx returned

for every HTTP request the application makes.

+7
angularjs angular
source share
1 answer

You can create your own HTTPConnection, which processes the error and injects it into the root component of the application at boot time.

 export class CustomHTTPConnection implements Connection { } 

and then enter it at boot as follows

 bootstrap([provider(Connection,{useClass:CustomHTTPConnection}]); 

If you want, do not want to provide your own connection class, you can do this for each individual request, since Http returns an observable, which has 3 parameters: onNext, onError, onCompleted.

You can use it as follows:

 class Component { constructor(private httpService:HttpService){ } onInit(){ this.httpService.getData().subscribe( ()=>{}, //on Next ()=>{} //onError } } 
+3
source

All Articles