如何防止以角度 4 刷新页面 [英] How to prevent page refresh in angular 4

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

问题描述

我想防止到处刷新页面.

I want to prevent page refresh by everywhere.

我尝试了下面的代码

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 或 JavaScript 的解决方案,而不是 jQuery.

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
    });
}

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

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