我正在使用Angular 2 RC2.我需要将Angular 2路由器注入我的自定义ExceptionHandler类.但是我收到以下错误
Error: Error: Cannot resolve all parameters for ‘ErrorHandler'(?).
Make sure that all the parameters are decorated with Inject or have
valid type annotations and that ‘ErrorHandler’ is decorated with
Injectable.
我确实试过装饰私有路由器:使用@Inject的路由器无济于事.我正在使用打字稿,因此我认为我不需要@Inject属性.
我的自定义ExceptionHandler看起来像这样
import { ExceptionHandler } from '@angular/core'; import { Router } from '@angular/router'; export class ErrorHandler extends ExceptionHandler{ constructor( private router: Router ){ super(null,null); } call(error,stackTrace = null,reason = null) { console.log(error); this.router.navigate(['/error']); } }
我的主要看起来像这样
import { bootstrap } from '@angular/platform-browser-dynamic'; import { AppComponent } from './app.component'; import { provide,ExceptionHandler } from '@angular/core'; import { ErrorHandler } from './error-handler/error-handler'; import { HTTP_PROVIDERS } from '@angular/http'; import { ROUTER_PROVIDERS } from '@angular/router'; bootstrap(AppComponent,[ HTTP_PROVIDERS,ROUTER_PROVIDERS,provide(ExceptionHandler,{useClass: ErrorHandler}) ]);
为什么我收到此错误?在ExceptionHandler实例化时,路由器是否可注入?
完整的源代码可在此处获得
https://github.com/harindaka/angular2-seed-typescript/tree/b368315ce6608085f3154a03bc53f0404ce16495
解决方法
见:
ErrorHandler班.您可以添加Injectable装饰器来实现DI!
import { ErrorHandler,Injectable } from '@angular/core'; @Injectable() export class GlobalErrorHandler implements ErrorHandler { private myService: MyService; constructor(private injector: Injector) { this.myService = injector.get(MyService); } handleError(error) { alert('Bad things happening'); } } @NgModule({ providers: [ { provide: ErrorHandler,useClass: GlobalErrorHandler } ] }) export class AppModule { }
注意:上面的答案使用ExceptionHandler,它在最终版本中被删除,有利于ErrorHandler.