Last active
September 20, 2024 08:58
-
-
Save Mustafa-Omran/0b411c89deef26a155273b9860735396 to your computer and use it in GitHub Desktop.
Angular +17 Interceptor (HttpInterceptorFn)
This file contains hidden or 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 { User } from '@amaleyat/shared/models/user'; | |
| import { isPlatformBrowser } from '@angular/common'; | |
| import { HttpInterceptorFn } from '@angular/common/http'; | |
| import { inject, PLATFORM_ID } from '@angular/core'; | |
| export const authInterceptor: HttpInterceptorFn = (req, next) => { | |
| const platformId: Object = inject(PLATFORM_ID); | |
| if (isPlatformBrowser(platformId)) { | |
| const user: User = JSON.parse(localStorage.getItem('user') || '{}'); | |
| if (user?.access_token) { | |
| const authReq = req.clone({ | |
| setHeaders: { | |
| 'Accept': '*', | |
| 'Content-Type': 'application/json', | |
| 'Authorization': `Bearer ${user?.access_token}`, | |
| }, | |
| }); | |
| return next(authReq); | |
| } | |
| } | |
| return next(req); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment