Angular2:在myExceptionhandler中注入路由器

时间:2016-10-13 06:44:18

标签: angular typescript

app.module.ts我有:

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        HttpModule
    ],
    providers: [
        {provide: ErrorHandler, useClass: MyExceptionHandler}
    ],
    bootstrap: [AppComponent],
})
export class AppModule {}

然后在我的MyExceptionHandler

import { Injectable } from "@angular/core"
import { Router } from "@angular/router"

@Injectable()
export class MyExceptionHandler {
    constructor (private _router: Router) {}

    handleError(error:any):void {
        ...
    }
}

但是,我收到错误消息:Error: Error: Provider parse errors

如果我使用MyExceptionHandler作为常规提供程序,它可以正常工作。所以我的猜测是在Router完全存在之前处理ErrorHandler。无论如何要解决这个问题?

1 个答案:

答案 0 :(得分:4)

根据https://github.com/angular/angular/issues/9843工作代码如下:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
    private _router: Router;
    constructor(private _injector: Injector) {
        // The true parameter tells Angular to rethrow exceptions, 
        // so operations like 'bootstrap' will result in an error
        // when an error happens. If we do not rethrow, 
        // bootstrap will always succeed.
        super(true);
    }

    handleError(error: any): void {
        // Delegate to the default handler.
        super.handleError(error);

        if (!this._router) {
            this._router = this._injector.get(Router);
        }

        // TODO: log error and then redirect to 500 page.
        this._router.navigate(['/errors/500']);
    }
}