我想在我的自定义错误处理程序中调用rest API,以便在调用处理程序时通过电子邮件发送给自己。
我尝试使用喷油器,但出现此错误:
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);
}
}
我也可能会说错方法,所以如果您能帮助我,那太好了!
答案 0 :(得分:2)
您应该使用http interceptor处理httpClient错误。在拦截器中,您可以注入所需的服务。但是,您应该注意从拦截器调用http请求,因为它将通过拦截器运行,并且当错误邮件程序关闭时,您最终可能会出现循环。