我收到此错误:
提供程序解析错误:无法实例化循环依赖!
我有一个组件可以对我的后端进行 http 调用:
backend.component.ts
import { HttpClient } from '@angular/common/http';
public basicQuery(): void {
this.httpClient.get('http://...')
.subscribe(
(response) => {
},
error => {
});
}
我每次通话都使用拦截器。
token.interceptor.ts
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
token: this.auth.getToken()
}
});
return next
.handle(request)
.do(
(response: HttpEvent<any>) => {
},
(error: any) => {
return false;
});
}
如果我收到错误,我会在我的自定义错误处理程序中处理它,因为我想将错误发送到我的后端。
自定义错误处理程序.ts
handleError(error): void {
this.errorLogService.logServer(error);
super.handleError(error);
}
因此我使用服务。
errorLog.service.ts
import { HttpClient } from '@angular/common/http';
logServer(error: Error) {
this.httpClient.post('http://...', JSON.stringify(error.message))
.subscribe(
(response) => { },
(error) => { });
}
这就是问题所在,因为我也使用 httpClient。但是我怎样才能避免这种失败,如何做对呢?现在我使用'Http'而不是'HttpClient'。
更新 1
private auth: AuthService;
constructor(
private utils: Utils,
private router: Router,
private injector: Injector
) {
this.auth = this.injector.get(AuthService);
}
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
token: this.auth.getToken()
}
});
return next
.handle(request)
.do(
(response: HttpEvent<any>) => { },
(error: any) => { return false }
);
}
更新 2
将 AuthService 和 Router 注入 body 可以解决问题:
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
this.auth = this.injector.get(AuthService);
this.router = this.injector.get(Router);
(...)
}