File
Methods
intercept
|
intercept(request: HttpRequest, next: HttpHandler)
|
|
Parameters :
Name |
Type |
Optional |
request |
HttpRequest<any>
|
No
|
next |
HttpHandler
|
No
|
Returns : Observable<HttpEvent<any>>
|
import 'rxjs/add/operator/do';
import {
HttpErrorResponse,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
HttpResponse
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { LogService } from '../services/log.service';
import { AuthService } from '../services/auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(public auth: AuthService, private logger: LogService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`,
'Cache-Control': 'no-cache', // HTTP 1.1
Pragma: 'no-cache', // HTTP 1.0
Expires: '-1' // Proxies
}
});
return next.handle(request).do(
// (event: HttpEvent<any>) => {
// if (event instanceof HttpResponse) {
// this.logger.log(event);
// }
// },
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
this.logger.log(err);
this.auth.logout();
}
}
}
);
}
}