import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { Observable, from } from '{{&observableImport}}'; import {REST_AUTH_TOKEN, RestAuthService} from './rest-auth-service'; import {REST_TOKEN_TOKEN, RestTokenService} from './rest-token-service'; @Injectable() export class JWTInterceptor implements HttpInterceptor { constructor(@Inject(REST_AUTH_TOKEN) private _authService: RestAuthService, @Inject(REST_TOKEN_TOKEN) private _tokenService: RestTokenService) { } intercept(req: HttpRequest, next: HttpHandler): Observable> { return from(this.handle(req, next)); } async handle(req: HttpRequest, next: HttpHandler): Promise> { try { await this._authService.silentRefresh(req); const token = this._tokenService.token(); if (token) { req = req.clone({ setHeaders: {authorization: 'Bearer ' + token} }); } } catch (e) { console.log('JWTInterceptor had an error'); console.log(e); } // always attempt the API, potentially w/o the authorization header: return next.handle(req).toPromise(); } }