Created
May 21, 2021 05:32
-
-
Save kudchikarsk/59eefb23b9a830a11ac121fc7a5c50f1 to your computer and use it in GitHub Desktop.
jwt.interceptor.ts
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 { Injectable } from '@angular/core'; | |
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; | |
import { Observable, throwError } from 'rxjs'; | |
import { AuthenticationService } from '../services/authentication.service'; | |
import { catchError } from 'rxjs/operators'; | |
import { Router } from '@angular/router'; | |
@Injectable() | |
export class JwtInterceptor implements HttpInterceptor { | |
constructor(private authenticationService: AuthenticationService, | |
private router:Router) {} | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
// add authorization header with jwt token if available | |
let currentUser = this.authenticationService.currentUserValue; | |
if (currentUser && currentUser.access_token) { | |
request = request.clone({ | |
setHeaders: { | |
Authorization: `Bearer ${currentUser.access_token}` | |
} | |
}); | |
} | |
return next.handle(request).pipe(catchError(err => { | |
if (err.status === 401) { | |
this.authenticationService.logout(); | |
this.router.navigate(['login']); | |
} | |
console.log(err); | |
const error = this.getModelState(err) || err.error?err.error.Message : undefined || err.statusText; | |
return throwError(error); | |
})); | |
} | |
getModelState(err) { | |
if(!err.error || !err.error.ModelState) return undefined; | |
let msg = []; | |
for(let key in err.error.ModelState) { | |
console.log(key) | |
for(let e of err.error.ModelState[key]) | |
msg.push(e); | |
} | |
return msg.shift(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment