首页 > 解决方案 > HttpInterceptor 在 Angular 6 中不起作用

问题描述

我正在使用HttpInterceptor添加身份验证令牌,问题是拦截器正在为第一个请求添加令牌,然后它停止工作。这是我的拦截器服务

import { Injectable } from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/internal/Observable";
import {CommonService} from "./common.service";

@Injectable({
  providedIn: 'root'
})
export class AuthInterceptorService implements HttpInterceptor {

  constructor(private auth: CommonService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authToken = this.auth.getAuthToken();
    const authReq = req.clone({ setHeaders: { Authorization: 'Bearer '+authToken.access_token} });
    return next.handle(authReq);
  }
}

这是应用程序模块提供程序部分

providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptorService,
    multi: true
  }],

让我知道代码有什么问题。

标签: angularcommand-line-interfaceangular-http-interceptors

解决方案


推荐阅读