加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2 RC 2如何将路由器注入自定义ExceptionHandler

发布时间:2020-12-17 06:51:24 所属栏目:安全 来源:网络整理
导读:我正在使用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 vali
我正在使用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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读