Angular 如何在离开页面之前显示确认警报?

Angular 如何在离开页面之前显示确认警报?,angular,Angular,我试图在离开页面之前显示确认警报,但在使用routerlink链接或返回上一页面时,该警报不起作用 我现在这样做了,它在关闭选项卡或重新加载页面时起作用 $(function(){ window.onbeforeunload = function (e) { e = e || window.event; if (e) { e.returnValue = 'Do you really want to leave?';

我试图在离开页面之前显示确认警报,但在使用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';
}

谢谢

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

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]},
@NgModule({
    ...
    providers: [
        ...
        ConfirmDeactivateGuard
    ]
 })
 export class AppModule {}