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
401
status code is returned5xx
status code is returnedfor every http request the application makes.
An error interceptor is a special kind of interceptor used for handling errors that happen when making HTTP requests. Errors come either from the client-side (browser) or the server-side when the request fails for some reason.
Whenever the error occurs in an HTTP operation, the Angular wraps it in an httpErrorResponse Object before throwing it back. We catch the httpErrorResponse either in our component class or in the data service class or globally. The Global HTTP error handling is done using the Angular HTTP Interceptor.
HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.
After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With