src/app/_helpers/token.interceptor.ts
Methods |
constructor(authService: AuthService, router: Router)
|
|||||||||
Defined in src/app/_helpers/token.interceptor.ts:16
|
|||||||||
Parameters :
|
intercept | |||||||||
intercept(request: HttpRequest
|
|||||||||
Defined in src/app/_helpers/token.interceptor.ts:22
|
|||||||||
Parameters :
Returns :
Observable<HttpEvent<any>>
|
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthService } from './services/auth.service';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(
private authService: AuthService,
private router: Router
) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (request.url.startsWith(environment.apiBaseUrl + '/api/token')) {
const token = this.authService.getToken();
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
}
}
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
this.authService.logout();
this.router.navigate(['/auth']);
}
return throwError(error);
})
);
}
}