Angular 路由器.x27;如果在ng生命周期挂钩期间发生错误,则无法工作

Angular 路由器.x27;如果在ng生命周期挂钩期间发生错误,则无法工作,angular,angular2-routing,Angular,Angular2 Routing,我有一个ErrorHandler,用于记录所有异常,然后将用户重定向到通用错误页面。问题是,只有当处理的异常发生在任何(或构造函数)外部时,这才起作用。方法。请考虑下面的例子: nGuniIT < /代码>: class MyErrorHandler implements ErrorHandler { constructor(private injector: Injector) { } handleError(error) { // log error var ro

我有一个
ErrorHandler
,用于记录所有异常,然后将用户重定向到通用错误页面。问题是,只有当处理的异常发生在任何(或构造函数)外部时,这才起作用。方法。请考虑下面的例子:<代码> nGuniIT < /代码>:

class MyErrorHandler implements ErrorHandler {
  constructor(private injector: Injector) { }

  handleError(error) {
    // log error

    var router = this.injector.get(Router);

     router.navigate['/error'];
  }
}
错误处理程序被正确调用。但是,router.navigate仅在组件初始化后发生异常时工作

不起作用:

import { Component, OnInit} from '@angular/core';
@Component({
  template: ''
})
export class SampleComponent implements OnInit{
    ngOnInit() {
    throw Error(`Boom!`);
  }
}
按预期工作:

import { Component, OnInit} from '@angular/core';
@Component({
  template: `<button (click)="handleClick()">click me</button>`
})
export class SampleComponent{
      private handleClick(): void{
        throw Error(`Boom!`);
    }
}
从'@angular/core'导入{Component,OnInit};
@组成部分({
模板:`单击我`
})
导出类SampleComponent{
私有handleClick():void{
抛出错误(`Boom!`);
}
}

我是不是错过了什么,或者我该怎么做?我想我可以使用
windows.location.href
,但这会重新加载页面,这是我宁愿避免的

MyErrorHandler中的注射不正确

在上的app.module.ts中更改
{provide:ErrorHandler,useClass:MyErrorHandler}

{
  provide: ExceptionHandler,
    useFactory: (router) => {
      return new MyErrorHandler(router);
    },
  deps: [Router]
}

现在您已经正确地注入了路由器。

过了一段时间,我觉得最好的解决方案确实是使用
'window.location.href'
将应用程序“重定向”到错误页面。您永远不知道最终会出现什么样的错误&在某些情况下,应用程序可能会完全崩溃

嘿,谢谢你的建议。尝试了此操作,但它给出了ApplicationRef的循环依赖项错误。也许值得注意的是,我在ErrorHandler中实例化的服务可以工作——我可以成功地调用我的服务并完成除路由之外的所有事情。我也有同样的问题,但在constructor(){}中抛出错误会按预期导航。