Angular 2自定义错误处理和路由器
发布时间:2020-12-17 06:58:57 所属栏目:安全 来源:网络整理
导读:我有一个自定义异常处理程序,如果发生任何异常(只是尝试它),它应该将用户带到自定义错误页面. 我试图使用Injector获取路由器的实例. 这样做的原因,我相信注入器将给现有的路由器实例并使用它我将能够路由用户. 任何想法为什么这不起作用或如何实现这一点?
我有一个自定义异常处理程序,如果发生任何异常(只是尝试它),它应该将用户带到自定义错误页面.
我试图使用Injector获取路由器的实例. 任何想法为什么这不起作用或如何实现这一点? 谢谢 :) @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中测试过 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,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,reason?:string):void { console.log('call...') this.router.navigate(['CustomErrorPage']); } } 并以这种方式注册您的句柄: bootstrap(MyApp,[ provide(ExceptionHandler,{useClass: AppExceptionHandler}) ]); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 如何在Scala中使lambda函数通用?
- 记录tibco webservice的一个错误异常 情况
- MiniProfiler:如何配置AngularJS WebAPI应用程序?
- 如何通过Docker Hub API确定标记的Docker镜像ID?
- 如何在bash中组合关联数组?
- angularjs – Angular 1.2:ng-bind-html删除img上的src属性
- 使用webService时,gsoap数据类型注意事项
- 【数据结构】冒泡排序
- angularjs – Angular TypeError:name.replace不是ng-styl
- 将angularjs webapp连接到REST API(PHP)