我想在自定义错误处理程序中调用其余 API,以便在调用处理程序时向自己发送电子邮件。
我尝试使用注入(inject)器,但收到此错误:
Error: Cannot instantiate cyclic dependency! HttpClient
在这里您可以看到我的错误处理程序:
import { Router } from '@angular/router';
import { ErrorHandler, Injector, Injectable, NgZone } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AppErrorHandler extends ErrorHandler {
constructor(private injector: Injector) {
super();
}
private get toastrService(): ToastrService {
return this.injector.get(ToastrService);
}
private get http(): HttpClient {
return this.injector.get(HttpClient);
}
private get router(): Router {
return this.injector.get(Router);
}
private get ngZone(): NgZone {
return this.injector.get(NgZone);
}
public handleError(error: any): void {
if (error.status === 401) {
this.ngZone.run(() => this.router.navigate(['/home']));
this.toastrService.error('Login first', 'Error');
} else if (error.status === 403) {
this.ngZone.run(() => this.router.navigate(['/home']));
this.toastrService.error('unauthorize', 'Error');
} else {
this.http.post<any>('/api/error-mailer', error).subscribe(() => { });
this.toastrService.error('Something went wrong', 'Error', { onActivateTick: true });
}
super.handleError(error);
}
}
我也可能有错误的方法,所以如果你能帮助我那就太好了!
最佳答案
您应该使用 http interceptor 处理 httpClient 错误。在拦截器中你可以注入(inject)你需要的服务。但是,您应该留意从拦截器调用 http 请求,因为它将通过拦截器运行,并且当您的错误邮件程序关闭时,您可能会陷入循环。
关于Angular如何在自定义ErrorHandler中使用HttpClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61141680/