我想使用Angular 7中的拦截器概念为每个API调用调用刷新API

时间:2019-07-18 09:15:20

标签: angular angular-httpclient angular-httpclient-interceptors

return this.httpClient.get(environment.baseUrl + 'users/refresh')

如何在以下代码中调用上述API,如何为每次调用将该令牌存储到本地存储中?

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { GlobalVariables } from '../utilities/constants';
export const InterceptorSkipHeader = 'X-Skip-Interceptor';

@Injectable()
export class AutherizationInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.headers.has(InterceptorSkipHeader)) {
     // console.log('if block')
      const headers = req.headers.delete(InterceptorSkipHeader);
    return next.handle(req.clone({ headers }));
    } else {
    //  console.log('else block ' + localStorage.getItem(GlobalVariables.AUTHERIZATION_TOEKN));
      const modified = req.clone({
        setHeaders:
        {
          'Authorization': 'Bearer ' + localStorage.getItem(GlobalVariables.AUTHERIZATION_TOEKN),
         'Content-Type': 'application/json'
        }
      });
      return next.handle(modified);
    }
  }
}

0 个答案:

没有答案