How to intercept request and response in Angular 6 and ad token to request? Well we will do all of that in this example.
Idea: create service which will be intercept every request and response. In case of request, we will modify header and ad token to it, and in case of response we will just create two different console logs in case of response error and i case when everything goes OK.
So first, let's create service, we will call it intercept service and it will be placed in services folder.
Open command line tool and type this:
ng g service services/intercept // g stands for generate
Open intercept.service.ts and paste this code:
import { Injectable } from '@angular/core';
import {AuthService} from '../services/auth.service';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse
} from '@angular/common/http'
import { Observable } from 'rxjs';
import { catchError,tap} from 'rxjs/operators';
@Injectable()//{providedIn: 'root'}
export class InterceptService implements HttpInterceptor {
constructor(private authService: AuthService) { }
// intercept request and add token
intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
// modify request
request = request.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.getItem('MY_TOKEN')}`
}
});
console.log("----request----");
console.log(request);
console.log("--- end of request---");
return next.handle(request)
.pipe(
tap(event => {
if (event instanceof HttpResponse) {
console.log(" all looks good");
// http response status code
console.log(event.status);
}
}, error => {
// http response status code
console.log("----response----");
console.error("status code:");
console.error(error.status);
console.error(error.message);
console.log("--- end of response---");
})
)
};
}
now let's add our service to app.module.ts
....
import { InterceptService} from './services/intercept.service';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
......
@NgModule({
declarations: [
...
],
imports: [
...,
HttpClientModule
],
providers: [InterceptService,
{
provide: HTTP_INTERCEPTORS,
useClass: InterceptService,
multi: true
}
],
bootstrap: [AppComponent]
})
And here is the example of modified request with included token in a header and response
If you like to show notification or error message when status is 4xx, check this post:
Angular 6 Material Snack Bar - fire when interceptor throws a error