gpt4 book ai didi

Angular 2 自定义错误处理和路由器

转载 作者:太空狗 更新时间:2023-10-29 17:28:41 26 4
gpt4 key购买 nike

我有一个自定义异常处理程序,如果发生任何异常(只需尝试一下),它应该将用户带到自定义错误页面。

我正在尝试使用 Injector 获取路由器实例。这样做的原因,我相信注入(inject)器将提供现有的路由器实例,并使用它我将能够路由用户。

为什么这不起作用或如何实现的任何想法?

谢谢你:)

@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"]);
}

}

Answer - 在 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"]);
}
}

}

最佳答案

我将以这种方式实现您的功能,因为此类发生在依赖项注入(inject)中:

@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})
]);

关于Angular 2 自定义错误处理和路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36765451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com