📜  在离开页面角度之前警告用户 - Javascript代码示例

📅  最后修改于: 2022-03-11 15:04:31.540000             🧑  作者: Mango

代码示例1
import { CanDeactivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean | Observable;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate {
  canDeactivate(component: ComponentCanDeactivate): boolean | Observable {
    // if there are no pending changes, just allow deactivation; else confirm first
    return component.canDeactivate() ?
      true :
      // NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
      // when navigating away from your angular app, the browser will show a generic warning message
      // see http://stackoverflow.com/a/42207299/7307355
      confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
  }
}