[英]Angular2 - How do I inject a service into a custom exception handler
我有一個像這樣的自定義異常處理程序,我試圖在其中注入服務(ErrorReportingService)
import { ExceptionHandler, Injectable } from '@angular/core';
import {ErrorReportingService } from '../services/ErrorReportingService';
@Injectable()
export class InsightsExceptionHandler extends ExceptionHandler {
constructor(private _errorReporter: ErrorReportingService) {
super(null, null);
}
call(error, stackTrace = null, reason = null) {
this._errorReporter.logError(error);
}
}
我試圖注入的服務看起來像這樣
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));
打破循環使用
@Injectable()
export class ErrorReportingService {
constructor(injector:Injector) {
setTimeout(() {
this.appRef = injector.get(ApplicationRef);
});
}
}
我不知道這是否正是導致循環的原因,因為您的問題不包含ErrorReportingService
源,但您應該明白這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.