Angular2 - 如何将服务注入(inject)自定义异常处理程序

标签 angular dependency-injection angular2-services angular2-injection

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

    }
}

我尝试注入(inject)的服务如下所示

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 已在应用程序组件的提供程序下注册。

我也尝试过以不同的方式注入(inject)服务,如下所示:

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 提供程序本身中添加您需要的所有服务,

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));

关于Angular2 - 如何将服务注入(inject)自定义异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38734416/

相关文章:

c# - 作为装饰者登录 vs. 依赖注入(inject)——如果我需要在类里面登录怎么办?

javascript - Angular 2 _this 未定义

javascript - 如何在 angularjs2 中使用日期过滤数据

angular - 如何防止组件更新服务

angular - 如何通过 @Input 装饰器通过引用而不是通过值将父属性传递给子组件?

Angular:如何解决SameSite Cookie问题

java - 错误 : [Dagger/MissingBinding] when trying building the project

asp.net-mvc - Unity 不解析依赖

javascript - 如何使用包含键作为字符串和值作为映射迭代的 ngFor 循环映射进行迭代

java - Angular向java发送错误的日期格式并且无法在表中创建对象