Angular 4 HttpInterceptor刷新令牌

时间:2017-09-22 10:31:12

标签: angular interceptor angular-http-interceptors

我有HttpInterceptor

import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, 
HttpRequest} from '@angular/common/http';
import {AuthService} from '../service/auth.service';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

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

  intercept(request: HttpRequest<any>, next: HttpHandler):     Observable<HttpEvent<any>> {
    const clone = request.clone({headers: request.headers.set(AuthService.AUTH, this.authService.getToken())});
    return next.handle(clone).catch(error => {
      if (error instanceof HttpErrorResponse && error.status === 401) {
        this.authService.clearToken();
        this.router.navigate(['/auth/signin']);
        return Observable.empty();
      }
      return Observable.throw(error);
    });
  }
}

我想在if块中刷新令牌,但是当我在构造函数中从HttpClient注入'@angular/common/http'时,我得到了异常:

    Uncaught Error: Provider parse errors:
Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
at NgModuleProviderAnalyzer.webpackJsonp.../../../compiler/@angular/compiler.es5.js.NgModuleProviderAnalyzer.parse (compiler.es5.js:11684)
at NgModuleCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.NgModuleCompiler.compile (compiler.es5.js:18497)
at JitCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.JitCompiler._compileModule (compiler.es5.js:26825)
at compiler.es5.js:26770
at Object.then (compiler.es5.js:1679)
at JitCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.JitCompiler._compileModuleAndComponents (compiler.es5.js:26768)
at JitCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.JitCompiler.compileModuleAsync (compiler.es5.js:26697)
at PlatformRef_.webpackJsonp.../../../core/@angular/core.es5.js.PlatformRef_._bootstrapModuleWithZone (core.es5.js:4536)
at PlatformRef_.webpackJsonp.../../../core/@angular/core.es5.js.PlatformRef_.bootstrapModule (core.es5.js:4522)
at Object.../../../../../src/main.ts (main.ts:11)

即使我通过http

注入一些具有刷新令牌逻辑的服务

2 个答案:

答案 0 :(得分:5)

您可以通过AuthService获取Injector。它可以帮助您避免DI错误。

constructor(
    private injector: Injector,
    private router: Router) {
}

然后而不是使用

this.authService

使用

this.injector.get(AuthService)

答案 1 :(得分:0)

您的authservice必须使用注入的http服务。所以尝试注入authservice如下:

constructor(private inj: Injector,
          private router: Router) {
    this.authService = inj.get(AuthService);
    ...

}

更多信息here

相关问题