Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function before refresh in Angular 2/4

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

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

using Angular2/4

like image 554
MeVimalkumar Avatar asked Jan 02 '18 12:01

MeVimalkumar


2 Answers

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

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

  ...
}
like image 110
ConnorsFan Avatar answered Nov 13 '22 23:11

ConnorsFan


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;
    }; 
like image 1
codeSetter Avatar answered Nov 13 '22 21:11

codeSetter