为了账号安全,请及时绑定邮箱和手机立即绑定

在离开页面之前警告用户未保存的更改

在离开页面之前警告用户未保存的更改

慕侠2389804 2019-11-07 10:17:19
我想警告用户未保存的更改,然后再离开我的angular 2应用程序的特定页面。通常,我会使用window.onbeforeunload,但不适用于单页应用程序。我发现在角度1中,您可以进入$locationChangeStart事件confirm为用户抛出一个框,但是我没有看到任何显示如何使角度2正常工作的东西,或者该事件是否仍然存在。我也看到过为ag1提供功能的插件onbeforeunload,但同样,我还没有看到将其用于ag2的任何方式。我希望其他人找到了解决该问题的方法;两种方法都可以很好地达到我的目的。
查看完整描述

3 回答

?
料青山看我应如是

TA贡献1772条经验 获得超7个赞

使用来自stewdebaker的@Hostlistener的示例确实运行良好,但是我对其进行了另一处更改,因为IE和Edge在MyComponent类上向最终用户显示了canDeactivate()方法返回的“ false”。


零件:


import {ComponentCanDeactivate} from "./pending-changes.guard";

import { Observable } from 'rxjs'; // add this line


export class MyComponent implements ComponentCanDeactivate {


  canDeactivate(): Observable<boolean> | boolean {

    // insert logic to check if there are pending changes here;

    // returning true will navigate without confirmation

    // returning false will show a confirm alert before navigating away

  }


  // @HostListener allows us to also guard against browser refresh, close, etc.

  @HostListener('window:beforeunload', ['$event'])

  unloadNotification($event: any) {

    if (!this.canDeactivate()) {

        $event.returnValue = "This message is displayed to the user in IE and Edge when they navigate without using Angular routing (type another URL/close the browser/etc)";

    }

  }

}


查看完整回答
反对 回复 2019-11-07
  • 3 回答
  • 0 关注
  • 779 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信