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

我想警告用户未保存的更改,然后再离开我的angular 2应用程序的特定页面。通常,我会使用window.onbeforeunload,但不适用于单页应用程序。

我发现在角度1中,您可以进入$locationChangeStart事件confirm为用户抛出一个框,但是我没有看到任何显示如何使角度2正常工作的东西,或者该事件是否仍然存在。我也看到过为ag1提供功能的插件onbeforeunload,但同样,我还没有看到将其用于ag2的任何方式。

我希望其他人找到了解决该问题的方法;两种方法都可以很好地达到我的目的。


慕侠2389804
浏览 782回答 3
3回答

料青山看我应如是

使用来自stewdebaker的@Hostlistener的示例确实运行良好,但是我对其进行了另一处更改,因为IE和Edge在MyComponent类上向最终用户显示了canDeactivate()方法返回的“ false”。零件:import {ComponentCanDeactivate} from "./pending-changes.guard";import { Observable } from 'rxjs'; // add this lineexport class MyComponent implements ComponentCanDeactivate {&nbsp; canDeactivate(): Observable<boolean> | boolean {&nbsp; &nbsp; // insert logic to check if there are pending changes here;&nbsp; &nbsp; // returning true will navigate without confirmation&nbsp; &nbsp; // returning false will show a confirm alert before navigating away&nbsp; }&nbsp; // @HostListener allows us to also guard against browser refresh, close, etc.&nbsp; @HostListener('window:beforeunload', ['$event'])&nbsp; unloadNotification($event: any) {&nbsp; &nbsp; if (!this.canDeactivate()) {&nbsp; &nbsp; &nbsp; &nbsp; $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)";&nbsp; &nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS