angular - 无法在 Angular 2 的 ErrorHandler 中定义带有参数的构造函数

标签 angular dependency-injection constructor

我正在尝试创建一个共享服务并从实现了 ErrorHandler 的 GlobalErrorHandler 类中使用它,但是当我使用参数编写构造函数时出现错误。

metadata_resolver.js:972 Uncaught SyntaxError {_nativeError: Error: Can't resolve all parameters for GlobalErrorHandler: (?).

全局错误处理器

export class GlobalErrorHandler implements ErrorHandler{

    constructor(private errorService:ErrorService){
        //When i write this without parameters no syntax error
    } 

    handleError(error){

        alert(error);
        console.log("handeled by GlobalErrorHandler")
        console.log("error",error);
        console.log("******************");
        //this.errorService.emitGlobalError("msgTest");
        //instead of logging to the console, i would like to call globalModal component and show the error in a popup
    }

}

错误服务

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class ErrorService {

    private globalErrorSource = new Subject<string>();
    globalErrorEmmitted= this.globalErrorSource.asObservable();

    emitGlobalError(msg){
            this.globalErrorSource.next(msg);
    }
}

应用模块

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,

  ],
  declarations: [

    ListMediaChannel,
    CrudMediaChannel
  ],
  providers: [SharedService, MovieCategoryService, MediaChannelService,ErrorService,
    {
      provide: LocationStrategy,
      useClass: PathLocationStrategy
    },
    {provide:ErrorHandler,useClass:GlobalErrorHandler}

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

最佳答案

带有构造函数参数的服务类需要`@Injectable()

@Injectable()
export class GlobalErrorHandler implements ErrorHandler{

在您的 ErrorService 上它是可选的,因为它没有构造函数参数。

关于angular - 无法在 Angular 2 的 ErrorHandler 中定义带有参数的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46368220/

相关文章:

angular - ionic 4 : Cannot read property 'get' of undefined

Angular 5 HttpInterceptor 并在 header 中发送授权 token

dependency-injection - 控制域对象构造问题的反转

javascript - javascript 构造函数序言的目的是什么?

java - 为什么 Java 没有像 C++ 中那样的初始化列表?

html - 如何取消选中 Angular 7 中单击按钮时的复选框

Angular 4从模态获取表单值

android - 无法创建自定义 ViewModel 的实例

c# - 将 appsettings 配置 DI 添加到 HostBuilder 控制台应用程序

templates - 为什么 Scala 辅助构造函数中不允许使用类型参数?