本文介绍了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块中的令牌,但是当我从构造函数中的'@angular/common/http'注入HttpClient时,我得到了异常:
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.NgModuleCompilerpile (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.JitCompilerpileModuleAsync (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注入一些具有刷新令牌逻辑的服务
Even if I'm injecting some Service which is has logic with refresh token through http
推荐答案您可以通过Injector获取AuthService.这将帮助您避免DI错误.
You can get AuthService via Injector. It will help you to avoid the DI error.
constructor( private injector: Injector, private router: Router) { }然后不使用
this.authService使用
this.injector.get(AuthService)更多推荐
Angular 4 HttpInterceptor刷新令牌
发布评论