Angular 2+: Interceptor
import {ApiAuthService} from './api-auth.service';
import {HttpRequest, HttpEvent, HttpHandler, HttpInterceptor} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: ApiAuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const copiedAuthRequest = req.clone({
setHeaders: {
Authorization: `Bearer ${this.authService.accessToken}`
}
});
return next.handle(copiedAuthRequest);
}
}