我得到此错误:
提供者解析错误:无法实例化循环依赖性!
我有一个组件可以对我的后端进行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;
});
}
如果我有错误,我在自定义错误处理程序中处理此错误,因为我想将错误发送到后端。
custom-error handler.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
将身份服务和路由器注入身体解决问题:
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);
(...)
}
这是您可以做到这一点的方法,不要在构造函数中注入服务,而是在函数体内进行。在这里,您也不会遇到诸如达到最大呼叫的问题。
@Injectable()
export class YourInterceptor implements HttpInterceptor {
yourService: YourService;
constructor(private inject: Injector) {
//this.yourService = inject.get(YourService);
}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
this.yourService = this.inject.get(YourService);
request = request.clone({
setHeaders: {
token: this.YourService.getToken()
}
});
return next.handle(request);
}
}
根据您的构造函数,请尝试一下
private auth: AuthService;
private router: Router;
constructor(
private utils: Utils,
private injector: Injector
) {
}
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.router = this.injector.get(Router);
this.auth = this.injector.get(AuthService);
request = request.clone({
setHeaders: {
token: this.auth.getToken()
}
});
return next
.handle(request)
.do(
(response: HttpEvent<any>) => { },
(error: any) => { return false }
);
}