如何用angular7显示google弹出确认对话框?

问题描述 投票:-1回答:1

我试图显示chrome弹出确认对话框后的修改,当我试图离开去另一个网址(路由)在我的应用程序。

enter image description here

我添加这个代码。

@HostListener('window:beforeunload', ['$event']) beforeUnload($event) {
     $event.returnValue = '';
  }

但当我尝试移动到另一个路线时,我没有得到任何确认对话框.我的工作与角度7.如何解决?如何解决这个问题呢,有什么例子吗,提前感谢。

angular7
1个回答
1
投票

Angular为Route事件提供了Guards。基于 文件 启用CanDeactivate Guard的功能,您可以在离开页面前显示确认对话框。

  @Injectable()
    class CanDeactivateExample implements CanDeactivate<YourComponent> {

      canDeactivate(
        component: YourComponent,
        currentRoute: ActivatedRouteSnapshot,
        currentState: RouterStateSnapshot,
        nextState: RouterStateSnapshot
      ): Observable<boolean|UrlTree>{

         if(component.isModified){
          return confirm('Are you sure to leave from page?');
        }
        return true;

      }
    }

要使用它,你需要编辑你的路由,如。

imports:[
...
    RouterModule.forRoot([
      {
        path: '<path>',
        component: YourComponent,
        canDeactivate: [CanDeactivateExample]
      }
    ])
]

而且Guard是可注入的,所以你需要在你的模块中提供它,你想在里面使用。

provides: [..., CanDeactivateExample]
© www.soinside.com 2019 - 2024. All rights reserved.