src/app/core/helpers/jwt.interceptor.ts
constructor(authenticationService: ApiAuthService)
|
intercept |
intercept(request: HttpRequest
|
Returns:
any
|
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '@environments/environment';
import { ApiAuthService } from '../services/auth/api.auth.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: ApiAuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const user = this.authenticationService.userValue;
const isLoggedIn = user && user.token;
const isApiUrl = request.url.startsWith(environment.apiUrl);
if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${user.token}`
}
});
}
return next.handle(request);
}
}