Angular 2自定义错误处理和路由器
问题描述:
我有一个自定义的异常处理程序,如果发生任何异常(只是试用它),应该将用户带到自定义错误页面。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"]);
}
}
}
答
因为这类发生在依赖注入我会实现你的功能是这样的:
@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
你找到这个问题的解决方案? – Scipion
嗨更新与答案的问题。 :) – ssujan728