auth.interceptor.ts 672 B

12345678910111213141516171819202122
  1. import { Injectable } from '@angular/core';
  2. import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
  3. import { Observable } from 'rxjs';
  4. import { AuthService } from './auth.service';
  5. @Injectable()
  6. export class AuthInterceptor implements HttpInterceptor {
  7. constructor(private auth: AuthService) {}
  8. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  9. const token = this.auth.getToken();
  10. if (token) {
  11. const authReq = req.clone({
  12. setHeaders: {
  13. Authorization: `Bearer ${token}`
  14. }
  15. });
  16. return next.handle(authReq);
  17. }
  18. return next.handle(req);
  19. }
  20. }