window.onbeforeunload-在Angular2中导入 [英] window.onbeforeunload - Importing in Angular2

查看:119
本文介绍了window.onbeforeunload-在Angular2中导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在项目中使用window.onbeforeunload,但我不知道如何使用它.

I am trying to use window.onbeforeunload in my project but I do not know how to use it.

我尝试了2种方法:

第一种方法

$(window).on("beforeunload", function(e) {
  return "Are you sure you want leave?";
});

第二种方式

    window.onbeforeunload = function (e) {
  //   e.returnValue = "hello, are you sure???";
    return "You may lose the changes!!!\n are you sure???";
  //   return null;
  };

我两个都出现错误,我猜这是因为我没有在某处导入某些东西.

I get errors in both of them and I guess that it is because I did not import something, somewhere.

此外,我想知道调用此事件时是否可以重定向到我网站的特定URL.

Furthermore, I would like to know if it is possible to redirect to an specific URL of my website when this event is called.

示例:按F5->/dashboard/

Example: Pressing F5 --> /dashboard/

推荐答案

您必须导入@HostListener并像下面在组件中一样使用它

you have to import @HostListener and use it like below in your component

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

export class TestComponent implements OnInit {
    @HostListener('window:beforeunload', ['$event']) onBeforeUnload(event) {
           // do something here 
          console.log("method called");
    }
}

这篇关于window.onbeforeunload-在Angular2中导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆