我们有要求我们必须提醒用户是否触摸了页面,如果使用选择不同的菜单应用程序应显示警告,如果用户继续继续,则应显示警告,然后只应重定向,否则它应该回退到同一页面。我们已尝试使用ngOnDestroy但是,应用程序正在重定向到下一页而不显示警报。
我的第一个方法是:
ngOnDestroy()
{
this.touched = this.eventForm.touched;
if (this.touched)
this.display = true;
}
现在我正在尝试使用CanDeactivate
后卫(请参阅this plunker示例):
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { SidebarComponent } from './shared/sidebar/sidebar.component';
@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<SidebarComponent> {
canDeactivate(target: SidebarComponent) {
if (target.hasChanges()) {
return window.confirm('Do you really want to cancel?');
}
return true;
}
}
答案 0 :(得分:4)
您应该使用canDeactivate
后卫
https://angular.io/api/router/CanDeactivate
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { SidebarComponent } from './shared/sidebar/sidebar.component';
@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<SidebarComponent> {
canDeactivate(target: SidebarComponent) {
if (target.hasChanges()) {
return window.confirm('Do you really want to cancel?');
}
return true;
}
}
参考Sample @plnkr https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html