如何在Angular 2中取消路线更改? [英] How to cancel route change in Angular 2?

查看:90
本文介绍了如何在Angular 2中取消路线更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在浏览器中单击后退或前进按钮时,我想取消路线更改. 到目前为止,我设法捕获了路线更改事件,如下面的代码所示:

I would like to cancel the route change when the user click back or forward button in the browser. So far I manage to capture the route change event as in the code below:

constructor(router:Router) {
  router.events
    .subscribe((event:Event) => {
      // some logic.
      // event.preventDefault(); ?
    });
}

我在事件中找不到任何方法/成员来停止事件默认值.然后,我将在控制台上收到此错误,因为我没有按预期注册路由配置,这是因为我使用location.go()修改了网址.

I couldn't find any method / member in event to stop the event default. Then I will get this error on console because I have no route config registered as intended, this is because I use location.go() to modify the url.

错误:未捕获(承诺):错误:不能匹配任何路由:'Some/Url'

Error: Uncaught (in promise): Error: Cannot match any routes: 'Some/Url'

有什么方法可以取消路线更改,以便Angular不用查看路线配置吗?

Is there any way to cancel the route change so Angular doesn't look at the route config?

推荐答案

在定义路线时可以使用canDeactivate保护,这将帮助您在更改路线时编写逻辑.

You may use canDeactivate guard when defining route, this will help you writing logic when changing route.

根据是要继续还是拒绝路线导航,您可以简单地返回true或false,您还可以引用对该路线处于活动状态的组件实例,以读取其上的任何属性.

You may simply return true or false, based upon if you want to continue or reject route navigation, you also get reference to your component instance which is active for that route so as to read any property on it.

方法的签名如下,

canDeactivate(component: T,
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot) :  
     Observable<boolean>|Promise<boolean>|boolean

您可能会在此处

这篇关于如何在Angular 2中取消路线更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆