当我在 HttpInterceptor 类中注入使用 HttpClient 的服务时,Angular 6 进入循环依赖的无限循环
Posted
技术标签:
【中文标题】当我在 HttpInterceptor 类中注入使用 HttpClient 的服务时,Angular 6 进入循环依赖的无限循环【英文标题】:Angular 6 enters infinite loop of cyclic dependency when I inject a service that uses HttpClient inside my HttpInterceptor class 【发布时间】:2018-12-10 23:54:38 【问题描述】:我在不同的 Angular 版本中多次发现这个问题,但多个消息来源说它已经修复,例如,*** 上的另一个类似问题是 this answer 说它已在 Angular 5.2 中解决,some other issues on Github are saying it solved in 6.0.2,我正在使用 Angular 6.0.3,但我仍然遇到这个问题,每当我尝试在我的 HttpInterceptor 类中注入使用 HttpClient 的服务时(如果在该服务中收到 jwt,则应该向请求添加一个 jwt 令牌)
我没有收到循环依赖的警告或错误,我可以在浏览器控制台中看到拦截器正在调用服务的数千个请求,反之亦然。
处理此问题的正确方法是什么?(最好不要将 jwt 存储在本地存储中)
(即使用拦截器并从服务中获取 jwt)
我的服务:
....
// only showing parts that matter, HttpClient is injected here
// to be used in calling the API services
constructor(public http: HttpClient, private route: ActivatedRoute,
public translate: TranslateService, private router: Router,
public snackBar: MatSnackBar, private notification: NotificationService)
//
我的 HttpInterceptor:
import Observable from 'rxjs';
import Location from '@angular/common';
import Injectable, Injector from '@angular/core';
import HttpInterceptor from '@angular/common/http';
import HttpRequest from '@angular/common/http';
import HttpHandler from '@angular/common/http';
import HttpEvent from '@angular/common/http';
import HttpHeaders from '@angular/common/http';
import DataService from './data/data.service';
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor
constructor(private injector: Injector)
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
const dataService = this.injector.get(DataService);
console.log('hey there, we are here INTERCEPTOR');
if (dataService.jwt)
request = request.clone(
setHeaders:
Authorization: `Bearer $dataService.jwt`
);
return next.handle(request);
ng 版本
Angular CLI: 6.0.8
Node: 10.0.0
OS: win32 x64
Angular: 6.0.7
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.6.3
@angular-devkit/build-angular 0.6.3
@angular-devkit/build-optimizer 0.6.3
@angular-devkit/core 0.6.3
@angular-devkit/schematics 0.6.8
@angular/cdk 6.1.0
@angular/cli 6.0.8
@angular/flex-layout 6.0.0-beta.15
@angular/material 6.3.1
@ngtools/webpack 6.0.3
@schematics/angular 0.6.8
@schematics/update 0.6.8
rxjs 6.2.1
typescript 2.7.2
webpack 4.8.3
【问题讨论】:
【参考方案1】:我可以通过自己在服务中实例化 HttpClient 来解决这个问题:
@Injectable()
export class DataService
private http: HttpClient;
constructor(httpBackend: HttpBackend)
this.http = new HttpClient(httpBackend);
这打破了我的情况下的无限循环问题(使用 Angular@6.1.10)。
【讨论】:
以上是关于当我在 HttpInterceptor 类中注入使用 HttpClient 的服务时,Angular 6 进入循环依赖的无限循环的主要内容,如果未能解决你的问题,请参考以下文章
SnackBar 在 HTTPInterceptor 中使用时不显示
安卓||在 Hilt 不支持的类中注入依赖项,例如 Helper 类
如何在 Blazor 类中注入服务(AuthenticationStateProvider)