Angular2-如何将服务注入自定义异常处理程序
我有一个像这样的自定义异常处理程序,我试图在其中注入一个服务(ErrorReportingService) 我尝试注入的服务如下所示Angular2-如何将服务注入自定义异常处理程序,angular,dependency-injection,angular2-services,angular2-injection,Angular,Dependency Injection,Angular2 Services,Angular2 Injection,我有一个像这样的自定义异常处理程序,我试图在其中注入一个服务(ErrorReportingService) 我尝试注入的服务如下所示 import { Http, Response } from '@angular/http'; import { Injectable, Inject } from '@angular/core'; @Injectable() export class ErrorReportingService { private ErrorReportingUrl =
import { Http, Response } from '@angular/http';
import { Injectable, Inject } from '@angular/core';
@Injectable()
export class ErrorReportingService {
private ErrorReportingUrl = `/property/insights/api/errorreporting`;
constructor(private _http: Http) { }
logError(error: any) {
var body = JSON.stringify(error);
this._http.post(this.ErrorReportingUrl, body, null);
}
}
ErrorReportingService在应用程序组件的提供程序下注册
我也尝试过以不同的方式注入服务,如下所示:
export class InsightsExceptionHandler extends ExceptionHandler {
private _errorReporter: ErrorReportingService;
constructor( @Inject(ErrorReportingService) errorReporter: ErrorReportingService) {
super(null, null);
this._errorReporter = errorReporter;
}
......
我在尝试运行应用程序时遇到此错误:
Error: (SystemJS) EXCEPTION: Error during instantiation of ApplicationRef_! (ApplicationRef -> ApplicationRef_).
ORIGINAL EXCEPTION: No provider for ErrorReportingService! (ExceptionHandler -> ErrorReportingService)
ORIGINAL STACKTRACE:
Error: DI Exception
我猜在你的应用程序主文件中,你正在引导你的应用程序,你必须使用类似于下面的异常处理方法 将您需要的所有服务添加到引导提供程序本身
bootstrap(
<YourAppComponent>,
[
// inject all the services which you need here
// so that they can be injected wherever required
ErrorReportingService,
provide(ExceptionHandler, {
useClass: InsightsExceptionHandler
})
]).catch(err => console.error(err));
bootstrap(
,
[
//在这里注入您需要的所有服务
//以便在需要的地方注射
错误报告服务,
提供(例外处理程序{
useClass:InsightsExceptionHandler
})
]).catch(err=>console.error(err));
要打破循环,请使用
@Injectable()
export class ErrorReportingService {
constructor(injector:Injector) {
setTimeout(() {
this.appRef = injector.get(ApplicationRef);
});
}
}
我不知道这是否正是导致循环的原因,因为您的问题不包含
ErrorReportingService
源代码,但您应该了解这一点。谢谢,我尝试过这个方法,但对我无效-相同的错误。服务的来源在问题中。哦,不知怎么的,我错过了。可能存在对ApplicationRef
的间接依赖。尝试注入Http
,就像我在回答中使用ApplicationRef
那样。这就是我尝试的。我想知道是否有什么东西在角度上发生了变化,正如我之前阅读并尝试了你之前建议的方式,我总是会遇到问题中提到的相同错误。我想我需要一个撞击器来调查。谢谢,这很有效。虽然我不知道;我不明白为什么我必须在bootstrap调用中提供它们,因为它们已经在应用程序组件的提供程序中了?我们通过在bootstrap中注册提供程序来覆盖默认的Angular ExceptionHandler,Angular根据服务的注册位置决定何时创建服务,因此在本例中,在bootstrap,因此,它将搜索同一级别上的所有依赖项,尽管您可能已在应用程序组件中添加了ErrorReportingService提供程序,该提供程序将为应用程序组件或子组件创建ErrorReportingService的新实例。希望这有帮助!!
@Injectable()
export class ErrorReportingService {
constructor(injector:Injector) {
setTimeout(() {
this.appRef = injector.get(ApplicationRef);
});
}
}