rexar1988
10/8/2018 - 4:45 PM

Angular 2+: Interceptor

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);
    }
}