在 Angular 5+ 中使用自定义 HttpInterceptors 时,我收到以下奇怪的依赖注入行为。
下面的简化代码可以正常工作:
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.auth.getToken();
return next.handle(req);
}
}
export class AuthService {
token: string;
constructor() {
console.log('AuthService.constructor');
}
}
然而....
当。。。的时候AuthService
其自身具有 1 个或多个依赖项,例如
export class AuthService {
token: string;
constructor(private api: APIService) {
console.log('AuthService.constructor');
}
}
角度正在尝试重复创建新实例AuthService
直到我收到以下错误:
日志显示的是AuthService.constructor
消息〜400次
and
Cannot instantiate cyclic dependency! HTTP_INTERCEPTORS ("[ERROR
->]"): in NgModule AppModule
and
app.component.html:44 错误 RangeError: 最大调用堆栈大小
超过
然后我尝试使用 Injector 类注入服务 -
export class AuthService {
token: string;
api: APIService;
constructor(private injector: Injector) {
this.api = this.injector.get(APIService);
console.log('AuthService.constructor');
}
}
但得到相同的错误(最大调用堆栈大小)。
The APIService
是一个简单的服务,只注入HttpClient
在它的构造函数中。
@Injectable()
export class APIService {
constructor(private http: HttpClient) {}
}
最后,当我注入AuthService
进入拦截器使用Injector
,错误消失,但 AuthService 被实例化 200 多次:
export class AuthInterceptor implements HttpInterceptor {
auth: AuthService;
constructor(private injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.auth = this.auth || this.injector.get(AuthService);
const token = this.auth.getToken();
return next.handle(req);
}
}
查看官方文档和其他示例,似乎在技术上可以将服务注入 Http 拦截器。是否有任何限制或可能缺少任何其他设置?