Philip
Philip

Reputation: 4208

How can I intercept http errors with angular2?

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

I want to be able to add interceptors at application startup that will

for every http request the application makes.

Upvotes: 7

Views: 1886

Answers (1)

Jigar
Jigar

Reputation: 544

You can create your own HTTPConnection that handles error and inject it into the root app component at bootstrap time.

export class CustomHTTPConnection implements Connection
{
}

and then inject it while bootstrapping as follows

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

If you want do not want to provide a custom connection class, you can do it for each individual request as Http returns an observable which as 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
}
}

Upvotes: 3

Related Questions