是否可以根据某些情况停止路由器导航 [英] Is it possible to stop router navigation based on some condition

查看:281
本文介绍了是否可以根据某些情况停止路由器导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,在某些情况下,我想在用户单击刷新按钮后退按钮时停止路由.我不知道这是否有可能,如果有人知道可以帮助我

I'm new to angular, I want stop the routing when user clicks on refresh button or back button based on some condition. I don't know whether this is possible, if anybody knows help me

constructor(private route: Router) {
    this.route.events
        .filter(event => event instanceof NavigationEnd)
        .pairwise().subscribe((event) => {
            if (expression === true){
                // stop routing 
            } else {
                // continue routing
            }      
        });
}

有可能吗?如果是,该怎么办?

Can it be possible? If yes, how can I do this?

推荐答案

事实发生后,我偶然发现了这个问题,但我希望能帮助到这里的其他人.

I stumbled upon this question quite a bit after the fact, but I hope to help someone else coming here.

解决方案的主要候选人是路由守卫.

The principal candidate for a solution is a route guard.

请参阅此处以获取说明: https://angular.io/guide/router#candeactivate-handling-unsaved-changes

See here for an explanation: https://angular.io/guide/router#candeactivate-handling-unsaved-changes

相关部分(几乎逐字复制)是此实现:

The relevant part (copied almost verbatim) is this implementation:

import { Injectable }           from '@angular/core';
import { Observable }           from 'rxjs';
import { CanDeactivate,
         ActivatedRouteSnapshot,
         RouterStateSnapshot }  from '@angular/router';

import { MyComponent} from './my-component/my-component.component';

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<MyComponent> {

  canDeactivate(
    component: MyComponent,
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | boolean {
    // you can just return true or false synchronously
    if (expression === true) {
      return true;
    }
    // or, you can also handle the guard asynchronously, e.g.
    // asking the user for confirmation.
    return component.dialogService.confirm('Discard changes?');
  }
}

其中MyComponent是您的自定义组件,而CanDeactivateGuard将在AppModule中的providers部分中注册,更重要的是,将在canDeactivate array属性中的路由配置中注册:

Where MyComponent is your custom component and CanDeactivateGuard is going to be registered in your AppModule in the providers section and, more importantly, in your routing config in the canDeactivate array property:

{
  path: 'somePath',
  component: MyComponent,
  canDeactivate: [CanDeactivateGuard]
},

这篇关于是否可以根据某些情况停止路由器导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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