我有一个Angular2应用程序。其中一个组件实现了CanDeactivate接口,以确认用户远离页面的导航。以下是路线保护的实施:
export class DeactivateGuard implements CanDeactivate<MyComponent> {
canDeactivate(component: MyComponent) {
let can = component.canDeactivate();
return can;
}
}
以下是组件的代码:
canDeactivate() {
if (confirm("Are you sure you want to navigate away?")) {
return true;
}
else {
return false;
}
}
现在,我想显示一个自定义模式窗口而不是浏览器的确认框。我用Telerik的Kendo UI构建了这样的窗口:
<kendo-dialog title="Please confirm" *ngIf="userConfirm">
Are you sure you want to navigate away?
<kendo-dialog-actions>
<button kendoButton class="k-button" (click)="closeConfirm('no')">No</button>
<button kendoButton class="k-button" (click)="closeConfirm('yes')" primary="true">Yes</button>
</kendo-dialog-actions>
</kendo-dialog>
如果我在代码中的任何地方设置 userConfirm = true ,则此模态窗口有效,但在canDeactivate()方法中除外。
canDeactivate() {
this.userConfirm = true; //Does not work. The modal does not show up.
}
如何使用此模态窗口获取用户的输入?
谢谢。
答案 0 :(得分:1)
我认为你从授权后卫执行component.canDeactivate();
时会失去范围。试试这个:
export class DeactivateGuard implements CanDeactivate<MyComponent> {
canDeactivate(component: MyComponent) {
return (() => component.canDeactivate())();
}
}
答案 1 :(得分:0)
我不确定Kendo是如何工作的,但是当你只使用confirm()时,你会在你的canDeactivate()函数中返回这个函数,如下所示:
canDeactivate() {
return confirm("Are you sure you want to navigate away?");
}
您可以阅读有关canDeactivate()here的更多信息。