Last active
January 10, 2023 13:39
-
-
Save rafaeldcastro/64a777a1aa73b5a3130312c5b24e197c to your computer and use it in GitHub Desktop.
Angular - Token HTTP Interceptor
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 { 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