角度-当用户离开一页(一个组件)时显示警报

时间:2018-07-16 09:04:00

标签: angular angular-forms angular-router angular-router-guards

预期的行为

我有一个页面,其中包含一种形式,当用户要离开此页面时,实际上它只是一个组件,我要显示一些警报,例如“您真的要离开此页面吗?您的更改将不会保存“。

当前行为

我尝试过

   @HostListener('window:beforeunload', ['$event'])
   yourfunction($event) {
     return $event.returnValue='Your changes will not be saved';
   }

但是对话没有出现。

任何想法或建议都将受到欢迎。

2 个答案:

答案 0 :(得分:0)

这是因为在Angular中,页面之间的过渡不是“真正的”过渡,并且window.beforeunload事件不会触发。要管理此问题,您必须使用Angular自己的路由器防护,特别是canDeactivate防护。这是有关canDeactivate防护的特定文档的link。您的实际代码可能看起来像这样:

@Injectable()
class DeactivateGuard implements CanDeactivate<YourComponent> {
    canDeactivate(){
//your popup logic goes here. Note that this method should return 
// a boolean, or a Promise/Observable of a boolean, if any async operations are present
   }
}

创建此防护后,只需将其放置在路线定义中即可

{path: 'path-to-your-component', component: YourComponent, canDeactivate: [DeactivateGuard]}

答案 1 :(得分:0)

您可以像在我的应用程序中一样使用canDeactivate
下面的示例

     @Injectable()
export class RouteLinkGuard implements CanDeactivate<Componentchanged> {
  constructor(private router: Router, private confirmationService: ConfirmationService, private commonService: CommonService) {}

  canDeactivate(Componentchanged: Componentchanged) {
// Here you can use whatever logic you want 
    if (this.commonService.getChangedValue() === true) {
      return Observable.create((observer: Observer<boolean>) => {
        this.confirmationService.confirm({
          message: 'Are you sure you want to leave this page? Any unsaved data would be lost?',
          header: 'Not saved',
          icon: 'fa fa-info',
          accept: () => {
            observer.next(true);
            observer.complete();
          },
          reject: () => {
            observer.next(false);
            observer.complete();
          }
        });
      });
    } else {
      return true;
    }
  }
}

//In Module
// You is like below
const routes: Routes = [
  {
    path: '',
    component: Componentchanged,
    canDeactivate: [RouteLinkGuard]
  }
];