2017-09-04 4 views
2

私は私が書いたカスタムエラーハンドラに角度資料2の要素を注入しようとしているが、私はこのエラーを取得しておいてください。角度(4):カスタムエラーハンドラ&DI:循環依存をインスタンス化することはできません

Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppModule in ./[email protected]:-1 

これは、エラーハンドラクラスです:

@Injectable() 
export class CustomErrorHandler implements ErrorHandler { 

    constructor(private snackBar: MdSnackBar) { 
    } 

    handleError(error: any): void { 
    //FIXME: display popup 
    console.error('Error occurred!'); 
    console.error(error); 
    this.snackBar.open('Application Error: ' + error, 'X', { 
     duration: environment.snackBarTime, 
    }); 
    } 

} 

これは、我々が持っているapp.module

providers: [ 
    SearchService, 
    CompanyService, 
    MdSnackBar, 
    PopupService, 
    AuthService, 
    LoginService, 
    AuthGuard, 
    ErrorService, 
    TokenStorageService, 
    BankService, 
    CountryService, 
    {provide: ErrorHandler, useClass: CustomErrorHandler}, 
    {provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}, 
    ], 
    exports: [ 
    TranslateModule 
    ], 
    bootstrap: [AppComponent] 
}) 

答えて

2

のプロバイダの一部であり、 handleError関数の実行時に手動でインジェクタにサービス名を呼び出すことができます。

私はInjectに組み込まれたサービス依存関係を注入する必要がありました。 MdSnackBar依存関係を持つPopupServiceを呼び出すcustom-error-handlerクラスの最終的な結果は次のようになります注入さ:

@Injectable() 
export class CustomErrorHandler implements ErrorHandler { 

    constructor(private injector: Injector) { 
    } 

    handleError(error: any): void { 
    console.log(error); 
    const popupService = this.injector.get(PopupService); 
    } 

} 

をそして、これはPopupServiceです:ここで言及

@Injectable() 
export class PopupService { 

    constructor(private snackBar: MdSnackBar) { 
    } 

    public throwErrorPopup(textOfError: string) { 
    this.snackBar.open(textOfError, 'X', { 
     duration: environment.snackBarTime, 
    }); 
    } 

} 

ソリューション:https://medium.com/@amcdnl/global-error-handling-with-angular2-6b992bdfb59c