import { Injectable } from '@angular/core'; import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { AuthService } from './auth.service'; import { catchError } from 'rxjs/operators'; import { AuthUiService } from './auth-ui.service'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor( private auth: AuthService, private authUi: AuthUiService ) {} intercept(req: HttpRequest, next: HttpHandler): Observable> { const token = this.auth.getAccessToken(); let authReq = req; if (token && !req.headers.has('Authorization')) { authReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); } return next.handle(authReq).pipe( catchError((err: HttpErrorResponse) => { if (err.status === 401) { this.auth.logout(); this.authUi.openSignin(); } return throwError(() => err); }) ); } }