[英]Angular 2 redirect in global ExceptionHandler
我正在嘗試實現一個將用戶重定向到錯誤頁面的ExceptionHandler。
為此,我需要注入一個路由器對象,如下所示:
@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
這有解決方案嗎? 是否可以在調用方法中實例化路由器,從而避免在對象創建期間出現循環依賴?
在已經實例化錯誤處理程序組件之后,注入Angular的注入器並在稍后階段獲取路由器實例:
constructor(private injector:Injector) {
super(null);
}
ngOnInit() {
this.router = this.injector.get(Router);
}
所以稍后您可以使用路由器實例:
call(exception:any, stackTrace?:any, reason?:string):void {
this.router.navigate(...);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.