1 import { Injectable, Injector } from '@angular/core'
6 HttpHandler, HTTP_INTERCEPTORS
7 } from '@angular/common/http'
8 import { Observable } from 'rxjs/Observable'
10 import { AuthService } from '../../core'
11 import 'rxjs/add/operator/switchMap'
14 export class AuthInterceptor implements HttpInterceptor {
15 private authService: AuthService
17 // https://github.com/angular/angular/issues/18224#issuecomment-316957213
18 constructor (private injector: Injector) {}
20 intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
21 if (this.authService === undefined) {
22 this.authService = this.injector.get(AuthService)
25 const authReq = this.cloneRequestWithAuth(req)
27 // Pass on the cloned request instead of the original request
28 // Catch 401 errors (refresh token expired)
29 return next.handle(authReq)
31 if (err.status === 401) {
32 return this.handleTokenExpired(req, next)
35 return Observable.throw(err)
39 private handleTokenExpired (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
40 return this.authService.refreshAccessToken()
42 const authReq = this.cloneRequestWithAuth(req)
44 return next.handle(authReq)
48 private cloneRequestWithAuth (req: HttpRequest<any>) {
49 const authHeaderValue = this.authService.getRequestHeaderValue()
51 if (authHeaderValue === null) return req
53 // Clone the request to add the new header
54 return req.clone({ headers: req.headers.set('Authorization', authHeaderValue) })
58 export const AUTH_INTERCEPTOR_PROVIDER = {
59 provide: HTTP_INTERCEPTORS,
60 useClass: AuthInterceptor,