Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Injectable } from '@angular/core';
  2. import {
  3.   HttpInterceptor,
  4.   HttpRequest,
  5.   HttpHandler,
  6.   HttpEvent,
  7.   HttpResponse,
  8.   HttpErrorResponse
  9. } from '@angular/common/http';
  10. import { Observable, throwError, BehaviorSubject, of } from 'rxjs';
  11. import { map, catchError, retry } from 'rxjs/operators';
  12. import { LoginService } from './../login/login.service';
  13. import { Router } from '@angular/router';
  14. import { ToastService } from 'libs/shared-components/src/lib/notification/notification.service';
  15. import { LoaderService } from '../loader.service';
  16.  
  17. @Injectable()
  18. export class AuthInterceptorService implements HttpInterceptor {
  19.   constructor(private loginService: LoginService, private router:Router, private toastService:ToastService, private service:LoaderService) {}
  20.  
  21.   private handleAuthError(err: HttpErrorResponse): Observable<any> {
  22.     if (err.status === 401 || err.status === 403) {
  23.         localStorage.clear();
  24.         this.router.navigateByUrl(`/login`);
  25.         return of(err.message);
  26.     }
  27. }
  28.  
  29.   intercept(
  30.     req: HttpRequest<any>,
  31.     next: HttpHandler
  32.   ): Observable<HttpEvent<any>> {
  33.     const token = this.loginService.getToken();
  34.     if (token) {
  35.       req = req.clone({
  36.         headers: req.headers.set('Authorization', 'Bearer ' + token)
  37.       });
  38.     }
  39.     if (!req.headers.has('Content-Type')) {
  40.       req = req.clone({
  41.         headers: req.headers.set('Content-Type', 'application/json')
  42.       });
  43.     }
  44.     req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
  45.     return next.handle(req).pipe(catchError( x => this.handleAuthError(x)));
  46.   }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement