Angular 4 HttpInterceptor refresh token

2019-06-10 09:43发布

问题:

I have 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);
    });
  }
}

And I want to refresh token in if block, but when i'm injecting HttpClient from '@angular/common/http' in constructor, I'm getting exception:

    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)

Even if I'm injecting some Service which is has logic with refresh token through http

回答1:

You can get AuthService via Injector. It will help you to avoid the DI error.

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

and then instead of using

this.authService

use

this.injector.get(AuthService)


回答2:

Your authservice must be using injected http service. So try injecting authservice as below:

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

}

More info here