File

src/app/services/auth.interceptor.ts

Index

Properties
Methods

Constructor

constructor(auth: AuthService, logger: LogService)
Parameters :
Name Type Optional
auth AuthService no
logger LogService no

Methods

intercept
intercept(request: HttpRequest, next: HttpHandler)
Parameters :
Name Type Optional
request HttpRequest<any> no
next HttpHandler no
Returns : Observable<HttpEvent<any>>

Properties

Public auth
auth: AuthService
Type : AuthService
import 'rxjs/add/operator/do';

import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { AuthService } from './auth.service';
import { LogService } from './log.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService, private logger: LogService) {}
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request).do(
      // (event: HttpEvent<any>) => {
      //   if (event instanceof HttpResponse) {
      //     this.logger.log(event);
      //   }
      // },
      (err: any) => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 401) {
            this.logger.log(err);
            this.auth.logout();
          }
        }
      }
    );
  }
}

results matching ""

    No results matching ""