2016-04-21 44 views
6

我有一個自定義的異常處理程序,如果發生任何異常(只是試用它),應該將用戶帶到自定義錯誤頁面。Angular 2自定義錯誤處理和路由器

我想獲得使用噴油器的路由器的實例。 這樣做的原因,我相信噴油器會給現有的路由器實例和使用它,我將能夠路由用戶。

任何想法爲什麼這不起作用或如何實現?

謝謝:)

@Injectable() 
export class AppExceptionHandler extends ExceptionHandler{ 

constructor(){ 
    super(null, null); 
} 

call(exception:any, stackTrace?:any, reason?:string):void { 
    console.log('call...') 


    var providers = Injector.resolve([ROUTER_PROVIDERS]); 
    var injector = Injector.fromResolvedProviders(providers); 

    // this is causing issue, not sure it is the correct way 
    let router : Router = injector.get(Router); 

    // not executed 
    console.log(router) 

    // not executed 
    console.log('done...') 
    router.navigate(["CustomErrorPage"]); 
    } 

} 

回答 - 在2.0.0-beta.17測試 由於Druxtan

 
1. Created a file app.injector.ts inside the app folder (app/app.injector.ts) 
let appInjectorRef; 

export const appInjector = (injector?) => { 
    if (!injector) { 
     return appInjectorRef; 
    } 

    appInjectorRef = injector; 

    return appInjectorRef; 
}; 
 
2. Added to the bootstrap in the main.ts 
bootstrap(AppComponent,[ROUTER_PROVIDERS, HTTP_PROVIDERS,provide(ExceptionHandler,{useClass : AppExceptionHandler})]) 
    .then((appRef) => appInjector(appRef.injector)); 
 
3. In the AppExceptionHandler, retrieved the Router instance as shown below 
export class AppExceptionHandler { 

    call(exception:any, stackTrace?:any, reason?:string):void { 

     let injectorApp = appInjector(); 
     let router = injectorApp.get(Router); 
     let localStorageService = injectorApp.get(LocalStorageService); 

     if(exception.message === '-1'){ 
      localStorageService.clear(); 
      router.navigate(["Login"]); 
     } 
    } 

} 
+0

你找到這個問題的解決方案? – Scipion

+0

嗨更新與答案的問題。 :) – ssujan728

回答

1

因爲這類發生在依賴注入我會實現你的功能是這樣的:

@Injectable() 
export class AppExceptionHandler extends ExceptionHandler { 
    constructor(private router:Router) { 
    super(null, null); 
    } 

    call(exception:any, stackTrace?:any, reason?:string):void { 
    console.log('call...') 

    this.router.navigate(['CustomErrorPage']); 
    } 
} 

,並註冊您的手柄是這樣的:

bootstrap(MyApp, [ 
    provide(ExceptionHandler, {useClass: AppExceptionHandler}) 
]); 
+0

謝謝你的建議 最初它是這樣做的。它仍然給我一些問題。從錯誤消息看起來好像AppExceptionHandler在Router之前被初始化,因此它不能被注入。 我嘗試這樣做太 '自舉(MyApp的,[ROUTER_PROVIDERS, 提供(的ExceptionHandler,{useClass:AppExceptionHandler}) ]);' 甚至沒有工作,這就是爲什麼我swithced到注射器。 – ssujan728