在角度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');
}
}
Run Code Online (Sandbox Code Playgroud)
然而....
当AuthService具有1个或更多依赖性时,例如
export class AuthService {
token: string;
constructor(private api: APIService) {
console.log('AuthService.constructor');
}
}
Run Code Online (Sandbox Code Playgroud)
angular尝试重复创建新实例,AuthService直到收到以下错误:
日志显示AuthService.constructor消息~400次
和
Cannot instantiate cyclic dependency! HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule
和
app.component.html:44错误RangeError:超出最大调用堆栈大小
然后我尝试使用Injector类注入服务 -
export class AuthService {
token: …Run Code Online (Sandbox Code Playgroud)