Created
July 25, 2023 06:47
-
-
Save Sathasivamthirumoorthi/6f05c2545299c68cc1b684c8ed346775 to your computer and use it in GitHub Desktop.
auth-header.interceptor.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; | |
import { Observable } from 'rxjs'; | |
import { CredentialsService } from '../services/auth'; | |
import { environment } from '@environments/environment'; | |
@Injectable() | |
export class AuthHeadersInterceptor implements HttpInterceptor { | |
constructor(private credentials: CredentialsService) { } | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
const user = this.credentials.userValue; | |
const isLoggedIn = user && user.token; | |
const isApiUrl = request.url.startsWith(environment.baseUrl); | |
if (isLoggedIn && isApiUrl) { | |
request = request.clone({ | |
setHeaders: { | |
Authorization: `Bearer ${user.token}` | |
} | |
}); | |
} | |
return next.handle(request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment