What is httpinterceptor equivalent in angular2?
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?
Solution 1:
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:
- Handling refresh tokens using rxjs
- Angular 2 - How to get Observable.throw globally
Solution 2:
update
The new HttpClient
module introduced in Angular 4.3.0 supports interceptors https://github.com/angular/angular/compare/4.3.0-rc.0...4.3.0
feat(common): new HttpClient API HttpClient is an evolution of the existing Angular HTTP API, which exists alongside of it in a separate package, @angular/common/http. This structure ensures that existing codebases can slowly migrate to the new API.
The new API improves significantly on the ergonomics and features of the legacy API. A partial list of new features includes:
- Typed, synchronous response body access, including support for JSON body types
- JSON is an assumed default and no longer needs to be explicitly parsed
- Interceptors allow middleware logic to be inserted into the pipeline
- Immutable request/response objects
- Progress events for both request upload and response download
- Post-request verification & flush based testing framework
original
Angular2 doesn't have (yet) interceptors. You can instead extend Http
, XHRBackend
, BaseRequestOptions
or any of the other involved classes (at least in TypeScript and Dart (don't know about plain JS).
See also
- RFC: Http interceptors and transformers
- Introduce an interception mechanism
- Interceptors in Angular2
- Angular2 - set headers for every request
Solution 3:
There's an implementation for a Http @angular/core-like service in this repository: https://github.com/voliva/angular2-interceptors
You just declare the provider for that service on bootstrap, adding any interceptors you need, and it will be available for all the components.
import { provideInterceptorService } from 'ng2-interceptors';
@NgModule({
declarations: [
...
],
imports: [
...,
HttpModule
],
providers: [
MyHttpInterceptor,
provideInterceptorService([
MyHttpInterceptor,
/* Add other interceptors here, like "new ServerURLInterceptor()" or
just "ServerURLInterceptor" if it has a provider */
])
],
bootstrap: [AppComponent]
})