【问题标题】:Is there any lifecycle hook like window.onbeforeunload in Angular2?Angular2中是否有像window.onbeforeunload这样的生命周期钩子?
【发布时间】:2016-08-14 06:33:47
【问题描述】:

Angular2中有没有像window.onbeforeunload这样的生命周期钩子? 我已经在 stackoverflow 上搜索并搜索过,但一无所获

【问题讨论】:

    标签: angular lifecycle


    【解决方案1】:

    在 Angular 中,我们可以创建类似的东西。

    @HostListener('window:beforeunload')
    confirmLeavingPageBeforeSaving(): boolean {
      // if 0 display dialog
      // if 1 you can reload
      return !this.myBoolean; 
    }
    

    【讨论】:

      【解决方案2】:
      <div (window:beforeunload)="doSomething()"></div>
      

      @Component({ 
        selector: 'xxx',
        host: {'window:beforeunload':'doSomething'}
        ..
      )}
      

      @Component({ 
        selector: 'xxx',
        ..
      )}
      class MyComponent {
        @HostListener('window:beforeunload')
        doSomething() {
        }
      }
      

      这是监听全局事件的方法。我不知道是否支持此事件的特殊行为,其中返回值用作构象对话框的文本。

      你仍然可以使用

      export class AppComponent {  
        constructor() {
          window.onbeforeunload = function(e) {
            return 'Dialog text here.';
          };
        }
      }
      

      就像这里解释的https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

      【讨论】:

      • 不幸的是,所有 3 个选项都不起作用。它必须在父组件上吗?在子组件上,它不会触发事件。示例:window.onbeforeunload = function (e) { alert('事件触发!');}
      • 我更新了我的问题。当我在 Chrome 中离开页面时,代码(最后一个变体)会显示对话框。
      • @oddRaven 在下面查看我的答案
      • Chrome 不再支持自定义字符串:chromestatus.com/feature/5349061406228480
      • 在 Angular 4 中,使用
        的最佳解决方案对我有用。在我的情况下,如果窗口或所有选项卡都关闭,我想执行用户注销。
      【解决方案3】:

      这对我有用。在页面组件构造函数中定义

      window.addEventListener("beforeunload", (event) => {
         event.preventDefault();
         event.returnValue = "Unsaved modifications";
         return event;
      });
      

      仅当您想在卸载前提示用户时才定义returnValue

      仅当用户与页面交互(例如点击)时才起作用。

      【讨论】:

      • 仅当用户与页面交互(例如点击)时才起作用。我一直在刷新页面,认为它不起作用
      • 在我的服务中使用了它,我需要确保在选项卡获得锁定并同时关闭时重新打开由 localStorage 管理的关键部分(例如localStorage.removeItem()
      • @umutesen 你的评论救了我的命,非常感谢
      • @nicolas 也感谢您的解决方案
      【解决方案4】:

      这更像是一个补充说明而不是一个答案,但我现在无法真正发表评论。
      不过,我想补充一下:

      我不会说初始化逻辑太复杂,但如果您决定在组件初始化时添加事件侦听器,最好将其包含在 ngOnInit 而不是构造函数中:

      window.addEventListener('beforeunload', function (e) {
        e.preventDefault();
        e.returnValue = '...';
      });
      

      尤其是如果您在卸载之前包含其他逻辑。

      ngOnDestroy 上还有一篇很好的文章,它的作用类似于指令、管道和服务的析构函数。这两种方法都很方便,具体取决于您希望执行的操作。

      完整链接文字:
      https://wesleygrimes.com/angular/2019/03/29/making-upgrades-to-angular-ngondestroy.html

      归功于 Günter Zöchbauer 的原始答案

      【讨论】:

        【解决方案5】:

        iOS的重要提示

        beforeunload 事件不应该发生 - 可能是由于“滥用”程度较高 多年来。

        您可以按照Apple 的建议使用pagehide

        这是Page visibility API 的一部分。

        https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

        所以我似乎无法让pagehide 在桌面 chrome 上触发,我也无法让beforeunload 在 iOS Safari 上触发 - 所以你需要两者 - 但请确保不要触发你的代码两次。

        @HostListener('window:beforeunload')
        @HostListener('window:pagehide')
        

        【讨论】:

        • 在桌面 chrome 上完美运行:@HostListener('window:pagehide', ['$event']) onClose($event) { console.log('hello') } 所以你不需要同时使用两者
        【解决方案6】:

        Günter Zöchbauer 的回答在 两个 上略有错误,这对我有用:

        @Component({ 
          selector: 'xxx',
          ..
        )}
        class MyComponent {
          @HostListener('window:beforeunload', ['$event'])
          doSomething($event) {
            if(this.hasChanges) $event.returnValue='Your data will be lost!';
          }
        }
        

        与 Günter 的回答有两个主要区别:

        1. @HostListener 的参数应该是 window:beforeunload 而不是 window:onbeforeunload
        2. 处理程序不应返回消息,而应将其分配给$event.returnValue

        【讨论】:

        • 这段代码对我有用。不幸的是,当我关闭选项卡时,这不会在我的安卓手机中执行。有什么建议吗?
        • 2018 年 10 月更新,Angular 6:需要设置 $event.returnValue=true;。任何其他值都不起作用(false、null、字符串等)。
        • 在 Chrome 中返回字符串对我有用:@HostListener('window:beforeunload', ['$event']) handleUnload(e) { e.preventDefault(); e.returnValue = 'Wait!';}
        猜你喜欢
        • 2018-03-13
        • 2016-08-26
        • 2017-12-06
        • 2016-10-28
        • 2015-12-08
        • 2017-07-12
        • 1970-01-01
        • 2017-02-20
        • 2020-01-15
        相关资源
        最近更新 更多