how to alert user on click of browser back button in angular 4?

无人久伴 提交于 2019-12-22 18:46:38

问题


how to alert the user on click of browser back button in angular 4?

onpopstate gets called even when the page loads for the first time

import {  PlatformLocation } from '@angular/common';

    constructor( private platformLocation: PlatformLocation) {
        platformLocation.onPopState(() => {
          console.log("onPopState called");
          window.alert("your data will be lost");
        })
    }

回答1:


Add a candeactivate guard

can-deactivate-guard.service.ts

import {Observable} from 'rxjs';
import {CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';

export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate, 
                currentRoute: ActivatedRouteSnapshot,
                currentState: RouterStateSnapshot,
                nextState?: RouterStateSnapshot
                ) : Observable<boolean> | Promise<boolean> | boolean {
    return component.canDeactivate();
  }
}

in your routing setting

const route: Route = [
  {path: '', component: AppComponent, canDeactivate: [CanDeactivateGuard]}
]

Provide your can Deactivate guards in your app.module in providers array.

Consider the following component where I have variable to check changes Saved

export class AppComponent implements CanComponentDeactivate {
   changesSaved = false;
   onUpdateServer() {
     this.changesSaved = true;
   }
   canDeactivate() {
      if(this.changesSaved) {
        return true;
      } else {
        return confirm('Do you want to discard changes');
      }
   }
}



回答2:


You can use ngOnDestroy inside the component.It will be called automatically when component is going to be destroyed and you can then alert any warning.



来源:https://stackoverflow.com/questions/48699611/how-to-alert-user-on-click-of-browser-back-button-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!