访问下面的路径信息canDeactivate在新的angular2路由器中

时间:2016-07-19 18:11:18

标签: angular router

如何访问里面的下一条路线信息" canDeactivate"在angular2新路由器中守卫

1 个答案:

答案 0 :(得分:0)

我一直坚持同样的问题。在我的情况下,我的canDeactivate逻辑将有条件地取消/重定向下一个路由。在这一点上,希望有更好的方法,我使用以下解决方案

  1. 从我的组件中,挂钩到Router事件(特别是RoutesRecognized)以记录该路由供以后使用。
  2. 实施canDeactivate并使用保存的路由数据返回true或false。
  3. ngOnInit(): void {
    	this.tabbedSearch = this.profilesService.currentProfile.tabbedSearch;
    
    	this.router.events
    		.filter(e => e instanceof RoutesRecognized)
    		.map(e => <RoutesRecognized> e)
    		.subscribe((e) => {
    			this.lastRoute = e.state.root.firstChild.routeConfig.path;
    			this.lastParams = e.state.root.firstChild.params;
    		});
    }
    
    public canDeactivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    	// do not navigate away if we are doing tabbed search AND the new route is the article details view
    	if (this.tabbedSearch && this.lastRoute == "article/details/:type/:id/:version") {
    		this.tabbedDetails.push(Object.create(this.lastParams));
    
    		return false;
    	}
    	else {
    		return true;
    	}
    }

    (注意:您无法运行代码段,但由于某种原因,代码示例格式化无法正常呈现。)

    我真的,真的不喜欢这个,但没有找到任何其他方式。

相关问题