typescript 在 Angular 2/4 中刷新前执行函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48061430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:08:49  来源:igfitidea点击:

Execute function before refresh in Angular 2/4

angulartypescript

提问by MeVimalkumar

On HTMLpage, When user click / press F5button page refresh but before refresh I want to execute one function or a simple alert.

HTML页面上,当用户单击/按下F5按钮页面刷新但在刷新之前我想执行一个功能或一个简单的警报。

User can click on refresh button, press F5or Ctrl + R.

用户可以点击刷新按钮,按F5Ctrl + R.

using Angular2/4

使用Angular2/4

采纳答案by codeSetter

You need to rely on browser events here.

您需要在此处依赖浏览器事件。

window.onbeforeunload = (ev) => {
            this.myFunction();

            // OR

            this.yuorService.doActon().subscribe(() => {
                alert('did something before refresh');  
            });

             // OR

            alert('goin to refresh');

            // finally return the message to browser api.
            var dialogText = 'Changes that you made may not be saved.';
            ev.returnValue = dialogText;
            return dialogText;
    }; 

回答by ConnorsFan

The refresh of the page should trigger the event handler bound to window:beforeunload. This stackblitzshows how to implement it for the "Home" component, using HostListener. You can test the page refresh by executing it in full page mode.

页面刷新应触发绑定到 的事件处理程序window:beforeunload这个 stackblitz展示了如何为“Home”组件实现它,使用HostListener. 您可以通过在整页模式下执行来测试页面刷新。

import { Component, HostListener } from '@angular/core';

@Component({
    ...
})
export class HomeViewComponent {

  @HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) {
      console.log("Processing beforeunload...");
      // Do more processing...
      event.returnValue = false;
  }

  ...
}