Http interceptor for angular2. Built with angular-library-starter
- Registering interceptors globally
- Separate interceptors for requests and responses
- Modify requests (even url) from request interceptors
- Cancel requests from request interceptors
- Modify responses from response interceptors
- Interceptor Service is not coupled with Http Service
- Choose between overriding original Http Service or keep it and still use interceptors
- Support AOT.
To install this library, run:
$ npm install angular2-http-interceptor --save
First, write your interceptor.
import {Request, Response} from '@angular/http';
import {Inject} from '@angular/core';
import {Platform} from 'ionic-angular';
import {IHttpInterceptor} from 'angular2-http-interceptor';
export class AuthInterceptor implements IHttpInterceptor {
constructor(@Inject(Platform) private platform: Platform) {
}
before(request: Request): Request {
if (this.platform.is('cordova') && request.url.match(/^\/api-hk\//)) {
request.url = `http://yulonh.com${request.url}`;
}
return request;
}
}
Then add code HttpInterceptorModule.withInterceptors([AuthInterceptor])
in app.module.ts
file.
...
import {HttpInterceptorModule} from 'angular2-http-interceptor';
@NgModule({
...
imports: [
...
HttpInterceptorModule.withInterceptors( [{
deps: [Platform],
provide: HttpInterceptor,
useClass: AuthInterceptor,
multi: true
}])
],
bootstrap: [IonicApp],
entryComponents: [
...
],
providers: [...]
})
export class AppModule {
}
MIT © yulonh