Токен обновления Angular 4 HttpInterceptor

У меня 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


person user2870934    schedule 22.09.2017    source источник
comment
Возможно, уже слишком поздно, но вы можете попробовать следующее: stackoverflow.com/questions/47797180/   -  person Julio Guerra    schedule 13.12.2017


Ответы (2)


Вы можете получить AuthService через Injector. Это поможет вам избежать ошибки DI.

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

а затем вместо использования

this.authService

использовать

this.injector.get(AuthService)
person yurzui    schedule 22.09.2017

Ваш authservice должен использовать внедренный http-сервис. Поэтому попробуйте ввести authservice, как показано ниже:

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

}

Дополнительная информация здесь

person Surender Kherwa    schedule 22.09.2017