在使用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
有一个或多个自身依赖时,例如:
export class AuthService {
token: string;
constructor(private api: APIService) {
console.log('AuthService.constructor');
}
}
Angular尝试反复创建AuthService
的新实例,直到我收到以下错误:
日志显示AuthService.constructor
消息约400次
和
Cannot instantiate cyclic dependency! HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule
和
app.component.html:44 ERROR RangeError: Maximum call stack size exceeded
然后我尝试使用Injector类注入服务 -
export class AuthService {
token: string;
api: APIService;
constructor(private injector: Injector) {
this.api = this.injector.get(APIService);
console.log('AuthService.constructor');
}
}
但是出现了相同的错误(最大调用栈大小)。
APIService
是一个简单的服务,只在它的构造函数中注入 HttpClient
。
@Injectable()
export class APIService {
constructor(private http: HttpClient) {}
}
最后,当我使用Injector
将AuthService
注入拦截器时,错误消失了,但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 拦截器中注入服务是技术上可能的。是否存在任何限制或可能缺失的其他设置?
@Injectable({ providedIn: 'root' }) export class HttpErrorInterceptor implements HttpInterceptor {
,这对我有效。 - Diosney