how to alert user on click of browser back button

2019-05-26 14:05发布

问题:

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.