离开页面前如何显示确认提示?

时间:2019-11-27 21:39:42

标签: angular

我正试图在离开页面之前显示确认警报,但是当我使用具有routerlink的链接或返回上一页时,它不起作用

我目前正在执行此操作,并且在关闭标签页或重新加载页面时可以使用

 $(function(){
     window.onbeforeunload = function (e) {
        e = e || window.event;
        if (e) {
            e.returnValue = 'Do you really want to leave?';
        }
        return 'Do you really want to leave?';
    };
 });

我尝试了这个,但有时不起作用

@HostListener('window:beforeunload', ['$event']) yourfunction($event) {
  return $event.returnValue='Your changes will not be saved';
}

谢谢

2 个答案:

答案 0 :(得分:1)

看看我评论中提供的答案。听起来您想要一个CanDeactivate警卫。您当前的代码不适用于routerLink,因为更改客户端上的路由(例如,使用Angular)不会卸载窗口。

答案 1 :(得分:1)

cat filename | awk -F"," '{print $4}'
  

//并且在路由文件中提供根目录,如

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { ViewGuard } from './path of ViewGuard';

@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<ViewGuard > {

    canDeactivate(target: ViewGuard ) {
        if (target.hasChanges) {
            return window.confirm('cancel this page?');
        }
        return true;
    }

}
  

//已相应注册:

{path:'rootPath/', component: ViewGuard , canDeactivate:[ConfirmDeactivateGuard]},