Concept of Interceptors is used for intercepting the HTTP request and response in Angular 2. You can append values in your HTTP request before sending to the server. You can alter you server response before displaying it.
For example in every request you wanted to show a loader and after coming response from server you wanted to hide the loader this show and hide of loader can be manage with Interceptors.
If you wanted to send some authentication token in headers you can manage it through Interceptors.
Because we are intercepting the HTTP request here so we also can name it "HTTP Interceptors".
For using intercepters you need to install NPM intercepter module and for that run below command:
1
|
sudo npm install ng2-interceptors --save
|
app.module.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
.......
.......
import { InterceptorService } from 'ng2-interceptors';
import { XHRBackend, RequestOptions } from '@angular/http';
export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, serverURLInterceptor: ServerURLInterceptor) { // Add it here
let service = new InterceptorService(xhrBackend, requestOptions);
service.addInterceptor(serverURLInterceptor); // Add it here
return service;
}
@NgModule({
declarations: [
.....
],
imports: [
.....
],
providers: [
.....
ServerURLInterceptor,
{
provide: InterceptorService,
useFactory: interceptorFactory,
deps: [XHRBackend, RequestOptions, ServerURLInterceptor] // Add it here, in the same order as the signature of interceptorFactory
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
|
ServerURLInterceptor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
import { Interceptor, InterceptedRequest, InterceptedResponse } from 'ng2-interceptors';
import { Injectable } from '@angular/core'
import { XHRBackend, RequestOptions, RequestOptionsArgs, Response, Headers } from '@angular/http';
import { CommonService } from '../services/index';
@Injectable()
export class ServerURLInterceptor implements Interceptor {
//Interceptor for request
constructor(private commonService: CommonService) { }
//Interceptor for request
public interceptBefore(request: InterceptedRequest): InterceptedRequest {
// Do whatever with request: get info or edit it
this.commonService.displayLoader(true);
let headers = new Headers();
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
var lastword = request.url.split("/").pop();
console.log(lastword);
if (lastword != 'addTraining' && lastword != 'editTraining') {
// for json request
headers.append('Content-Type', 'application/json');
if (currentUser && currentUser.result.user.access_token) {
headers.append('AccessToken', currentUser.result.user.access_token );
// headers.append('responseType','arraybuffer');
}
}
else{
// for form request
if (currentUser && currentUser.result.user.access_token) {
headers.append('AccessToken', currentUser.result.user.access_token );
// headers.append('responseType','arraybuffer');
}
}
let options = new RequestOptions({ headers: headers, });
request.options.headers = headers;
return request;
}
//Interceptor for response
public interceptAfter(response: InterceptedResponse): InterceptedResponse {
// Do whatever with response: get info or edit it
this.commonService.displayLoader(false);
return response;
}
}
|
user.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
.....
import { InterceptorService } from 'ng2-interceptors';
@Injectable()
export class UserService {
constructor(private http: InterceptorService) { }
//FUNCTION TO GET LIST OF ALL USERS
getAll(name: string = null, page: number = 1) {
return this.http.post(Config.BASE_API_URL + '/users-list', { name: name, page: page}, {
})
.map(this.commonService.extractData)
.catch(this.commonService.handleError)
}
}
|