Guest User

Untitled

a guest
Oct 17th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. import { Injectable } from "@angular/core";
  2. import { AuthService } from "../services/auth.service";
  3. import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from "@angular/common/http";
  4. import { Observable, throwError } from "rxjs";
  5. import { catchError } from "rxjs/operators";
  6. import { Router } from "@angular/router";
  7.  
  8. @Injectable()
  9. export class TokenInterceptor implements HttpInterceptor {
  10. constructor(private auth: AuthService, private router: Router){
  11. }
  12.  
  13. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  14. if (this.auth.isAuthenticated()) {
  15. req = req.clone({
  16. setHeaders: {
  17. Authorization: this.auth.getToken()
  18. }
  19. })
  20. }
  21. return next.handle(req).pipe(
  22. catchError(
  23. (error: HttpErrorResponse) => this.handleAuthError(error)
  24. )
  25. )
  26. }
  27.  
  28. private handleAuthError(error: HttpErrorResponse): Observable<any> {
  29. if (error.status === 401) {
  30. this.router.navigate(['/login']), {
  31. queryParams: {
  32. sessionFailed: true
  33. }
  34. }
  35. }
  36.  
  37. return throwError(error)
  38. }
  39.  
  40. }
Add Comment
Please, Sign In to add comment