如何防止在Angle 4中刷新页面 [英] How to prevent page refresh in angular 4

查看:107
本文介绍了如何防止在Angle 4中刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阻止页面刷新.

我尝试了下面的代码

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CommonServices } from '../services/common.service'; 

@Component({
  selector: 'app-review-prescription',
  templateUrl: './review-prescription.component.html',
  styleUrls: ['../../assets/css/prescriptionView.css'],
  providers:[
    CommonServices
  ]
})
export class ReviewPrescriptionComponent implements OnInit {
    constructor(
        private commonServices:CommonServices,
        private router:Router
        ){}
    ngOnInit(){
      window.onbeforeunload = function(event) {
        return 'By refreshing this page you may lost all data.';
      }
  }

}

甚至在组件类之外也在ngOnChanges()ngOnInit()ngOnDestroy()上对此进行了尝试(对不起,这是不合逻辑的),但是没有任何作用?

Tried this on ngOnChanges(), ngOnInit(), ngOnDestroy() even outside the component class(sorry illogical) but nothing works?

我需要Angular或jQuery中不需要的JavaScript解决方案.

I need solution in Angular or JavaScript not in jQuery.

谢谢.

推荐答案

尝试以下订阅以刷新页面上的警报窗口.在尝试刷新或关闭窗口之前,请执行一些用户事件,例如单击页面. 在此处检查工作版本

Try the below subscription to throw alert window on page refresh. do some user events like click over the page before trying to refresh or close the window. check the working version here

请参阅有关beforeunload的官方文档

ngOnInit() {
    window.addEventListener("beforeunload", function (e) {
        var confirmationMessage = "\o/";
        console.log("cond");
        e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
        return confirmationMessage;              // Gecko, WebKit, Chrome <34
    });
}

这篇关于如何防止在Angle 4中刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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