Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sathasivamthirumoorthi/6f05c2545299c68cc1b684c8ed346775 to your computer and use it in GitHub Desktop.
Save Sathasivamthirumoorthi/6f05c2545299c68cc1b684c8ed346775 to your computer and use it in GitHub Desktop.
auth-header.interceptor.ts
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