File

src/app/_helpers/token.interceptor.ts

Index

Methods

Constructor

constructor(authService: AuthService, router: Router)
Parameters :
Name Type Optional
authService AuthService No
router Router No

Methods

intercept
intercept(request: HttpRequest, next: HttpHandler)
Parameters :
Name Type Optional
request HttpRequest<any> No
next HttpHandler No
Returns : Observable<HttpEvent<any>>
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthService } from './services/auth.service';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(
    private authService: AuthService,
    private router: Router
  ) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (request.url.startsWith(environment.apiBaseUrl + '/api/token')) {
      const token = this.authService.getToken();
      if (token) {
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${token}`,
          },
        });
      }
    }
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          this.authService.logout();
          this.router.navigate(['/auth']);
        }
        return throwError(error);
      })
    );
  }
}

results matching ""

    No results matching ""