Skip to content

Instantly share code, notes, and snippets.

@rafaeldcastro
Last active January 10, 2023 13:39
Show Gist options
  • Save rafaeldcastro/64a777a1aa73b5a3130312c5b24e197c to your computer and use it in GitHub Desktop.
Save rafaeldcastro/64a777a1aa73b5a3130312c5b24e197c to your computer and use it in GitHub Desktop.
Angular - Token HTTP Interceptor
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
/**SERVICES */
import { AuthService } from '@pages/auth/shared/services/auth/auth.service';
@Injectable({
providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {
constructor(private authService: AuthService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token = this.authService.token;
if (
!request.headers.has('Content-Type') &&
!request.url.includes('/anexo')
) {
request = request.clone({
headers: request.headers.set('Content-Type', 'application/json')
});
}
if (token) {
request = request.clone({
headers: request.headers.set('Authorization', `Bearer ${token}`)
});
}
return next.handle(request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment