2016-06-28 5 views
1

私はエラーページにユーザーをリダイレクトするExceptionHandlerを実装しようとしています。そのためにグローバルExceptionHandlerの角2リダイレクト

私はそうのようにルータオブジェクト注入する必要があります。

@Injectable() 
class RedirectExceptionHandler extends ExceptionHandler { 

    constructor(private router: Router) { 
    super(null, null); 
    } 

    call(error: any, stackTrace: any = null, reason: any = null) { 
    // ...log and redirect to error page 
    } 
} 

を、私はこのコードを実行するときしかし、私は例外を取得:

(index):87 Error: EXCEPTION: Error during instantiation of ApplicationRef_! (ApplicationRef -> ApplicationRef_). 
    ORIGINAL EXCEPTION: Cannot instantiate cyclic dependency! (ExceptionHandler -> Router -> ApplicationRef) 
    ORIGINAL STACKTRACE: 
    Error: DI Exception 
     at CyclicDependencyError.BaseException [as constructor] (http://localhost:1080/node_modules/@angular/core/src/facade/exceptions.js:17:23) 
     at CyclicDependencyError.AbstractProviderError[as constructor] (http://localhost:1080/node_modules/@angular/core/src/di/reflective_exceptions.js:39:16) 
     at new CyclicDependencyError(http://localhost:1080/node_modules/@angular/core/src/di/reflective_exceptions.js:102:16) 
     at ReflectiveInjector_._new (http://localhost:1080/node_modules/@angular/core/src/di/reflective_injector.js:613:19) 
     at ReflectiveInjectorDynamicStrategy.getObjByKeyId (http://localhost:1080/node_modules/@angular/core/src/di/reflective_injector.js:270:50) 
     at ReflectiveInjector_._getByKeyDefault (http://localhost:1080/node_modules/@angular/core/src/di/reflective_injector.js:795:38) 
     at ReflectiveInjector_._getByKey (http://localhost:1080/node_modules/@angular/core/src/di/reflective_injector.js:767:25) 
     at ReflectiveInjector_._getByReflectiveDependency (http://localhost:1080/node_modules/@angular/core/src/di/reflective_injector.js:757:21) 
     at ReflectiveInjector_._instantiate (http://localhost:1080/node_modules/@angular/core/src/di/reflective_injector.js:654:36) 
     at ReflectiveInjector_._instantiateProvider (http://localhost:1080/node_modules/@angular/core/src/di/reflective_injector.js:626:25) 
    Evaluating http://localhost:1080/app/main.js 
    Error loading http://localhost:1080/app/main.js 

は、このための解決策はありますか?代わりに呼び出しメソッドでルータをインスタンス化することができます。これにより、オブジェクト作成時の循環依存性を回避できますか?

答えて

0

を注入角度のインジェクタと、あなたのエラーハンドラコンポーネントが既にインスタンス化された後に、後の段階で、ルータのインスタンスを取得:

constructor(private injector:Injector) { 
    super(null); 
} 

ngOnInit() { 
    this.router = this.injector.get(Router); 
} 

ので、後であなたは、ルータのインスタンスを使用することができます上:

call(exception:any, stackTrace?:any, reason?:string):void { 
    this.router.navigate(...); 
} 
関連する問題