In angularjs, we have http interceptor
$httpProvider.interceptors.push('myHttpInterceptor');
with which we can hook into all http calls, and show or hide loading bars, do logging, etc..
What is the equivalent in angular2?
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.
To use the same instance of HttpInterceptors for the entire app, just import the HttpClientModule into your AppModule, and add the interceptor to the root application injector. Suppose you import HttpClientModule multiple times in different modules (for example, in a lazy-loading module).
To create an Interceptor, we need to implement the HttpInterceptor interface from @angular/common/http package. Every time our application makes an HTTP request using the HttpClient service, the Interceptor calls the intercept() method.
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.
As @Günter pointed it out, there is no way to register interceptors. You need to extend the Http
class and put your interception processing around HTTP calls
First you could create a class that extends the Http
:
@Injectable() export class CustomHttp extends Http { constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) { super(backend, defaultOptions); } request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { console.log('request...'); return super.request(url, options).catch(res => { // do something }); } get(url: string, options?: RequestOptionsArgs): Observable<Response> { console.log('get...'); return super.get(url, options).catch(res => { // do something }); } }
and register it as described below:
bootstrap(AppComponent, [HTTP_PROVIDERS, new Provider(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions), deps: [XHRBackend, RequestOptions] }) ]);
The request
and requestError
kinds could be added before calling the target methods.
For the response
one, you need to plug some asynchronous processing into the existing processing chain. This depends on your need but you can use operators (like flatMap
) of Observable.
Finally for the responseError
one, you need to call the catch
operator on the target call. This way you will be notified when an error occurs in the response.
This links could help you:
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