2

我有一个像这样的自定义异常处理程序,我试图在其中注入服务(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
4

2 回答 2

3

我猜在您引导应用程序的应用程序主文件中,您必须使用类似于下面的内容进行异常处理,

在引导提供程序本身中添加您需要的所有服务,

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));
于 2016-08-03T04:41:58.533 回答
0

打破循环使用

@Injectable()
export class ErrorReportingService {
  constructor(injector:Injector) {
    setTimeout(() {
      this.appRef = injector.get(ApplicationRef);
    });
  }
}

我不知道这是否正是导致循环的原因,因为您的问题不包含ErrorReportingService来源,但您应该明白这一点。

于 2016-08-03T05:07:01.443 回答