我已经在不同的Angular版本中多次发现了这个问题,但是多个消息来源说它已经修复了,例如,Stackoverflow上的另一个类似的问题是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标记)
我没有得到一个警告或错误,我有循环依赖,我可以在浏览器控制台中看到拦截器正在调用服务的数千个请求,反之亦然 .
What is the proper way to handle this issue? (最好不要将jwt存储在localstorage中)
(即使用拦截器并从服务中获取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来解决它:
这打破了我的无限循环问题(使用Angular@6.1.10) .