import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { UserService } from '../services/user.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthHeaderInterceptor implements HttpInterceptor {
constructor(private userService: UserService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.userService.isAuthenticated()) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${this.userService.token}`
}
});
}
return next.handle(req);
}
}
Providing Interceptor (some-module.module.ts)
{provide: HTTP_INTERCEPTORS, useClass: AuthHeaderInterceptor, multi: true},