简体   繁体   English

Angular 路由器(路由)-取消导航到不同的路由(url)

[英]Angular Router (Routing) - Cancel navigation to different route (url)

I have a component that should be destroyed each time the changes (for example, each time the user click to go back on history), but before the destruction of the component, I want to show a message asking if the user wants to leave without saving the changes.我有一个每次更改都应该销毁的组件(例如,每次用户点击 go 回到历史记录),但在组件销毁之前,我想显示一条消息,询问用户是否想离开保存更改。

The user can select the "no" answer, which the app should stop the navigation in this case.用户可以 select 回答“否”,在这种情况下应用程序应该停止导航。 If the user selects the "yes" answer, the navigation should continue.如果用户选择“是”答案,导航应该继续。

My question is, how can I do that?我的问题是,我该怎么做?

Follows an example:跟随一个例子:

export class ListConfigurationsComponent implements OnInit, OnDestroy {
   ...
   constructor(
        ...
        private router: Router) {

        router.events.subscribe((val) => {
            //Cancel the option here
        });
   }
}

try this using restoredState property, it's defined when the navigation is triggered by a popstate event otherwise it's null, check this尝试使用restoreState属性,当导航由popstate事件触发时定义,否则为 null,检查

router.events.pipe(
  filter(( event: NavigationEvent ) => {
        return( event instanceof NavigationStart );
       })
).subscribe((event: NavigationStart) => {
   if (event.restoredState ) {
      // display you confirmation modal
    }
})

You're looking for CanDeactivate Guard.您正在寻找 CanDeactivate Guard。 Check this article, it describes how to make generic CanDeactivate strategy: https://medium.com/@tobias.ljungstrom/how-to-use-a-custom-dialogue-with-the-candeactivate-route-guard-in-angular-385616470b6a查看这篇文章,它描述了如何制作通用 CanDeactivate 策略: https://medium.com/@tobias.ljungstrom/how-to-use-a-custom-dialogue-with-the-candeactivate-route-guard-in-角度385616470b6a

One version could be that you don't use the [routerLink] in your template.一个版本可能是您没有在模板中使用 [routerLink]。 Use the (click) handler instead to call your function which checks if the user should be redirected.使用 (click) 处理程序来调用您的 function 来检查是否应该重定向用户。

In your html在您的 html

(click) = "checkDialog()";

If so in your ts just use如果在您的 ts 中是这样,请使用

this.router.navigate(['/next-page']);

in your condition在你的情况下

A better approach would be to check for the navigationTrigger property on the NavigationEvent and check the previous state ID in the restoredState property as更好的方法是检查NavigationEvent上的navigationTrigger属性,并检查 restoreState 属性中以前的restoredState ID 为

if(event instanceof NavigationStart && event.navigationTrigger == "popstate" && event.restoredState)

Stackblitz at https://stackblitz.com/edit/angular-check-navigation-back-fron-through-browser Stackblitz 在https://stackblitz.com/edit/angular-check-navigation-back-fron-through-browser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM