Angular 4可以停止不尊重选择

时间:2017-09-14 14:14:30

标签: angular angular-ui-router

我为表单创建了一个简单的canDeactivate处理程序。当我尝试离开我的表单时,下面的函数会运行,我可以根据我点击的按钮确认订阅返回TRUE或FALSE。但无论订阅返回的结果如何,Angular都不会离开我的表单。有人可以解释原因吗?

public canDeactivate(): Subscription {
  // Popup a prompt dialog
  const title = 'Lose Changes';
  const prompt = 'Are you sure you want to lose your changes';
  this.dialogWindow.show(EDialogTypes.EDialogYesNo, EDialogStyles.EDialogStyleWarning, title, prompt);

  // Based on the result allow leave or not
  this.subscription = this.dialogWindow.observable.subscribe(proceed => {
    console.log('Allow proceed: ' + proceed)
    console.log(this.dialogWindow.buttonPressed);
    // unsubscribe is necessary such that the observable doesn't keep racking up listeners
    this.subscription.unsubscribe();
    return proceed;
  });
  return this.subscription;
}

1 个答案:

答案 0 :(得分:0)

我设法找出一些基于其他SO问题的东西。

// Allow the user to navigate away from this page
public canDeactivate(): Observable<boolean> {

  // Popup a prompt dialog
  const title = 'Lose Changes';
  const prompt = 'Are you sure you want to lose your changes?';
  this.dialogWindow.show(EDialogTypes.EDialogYesNo, EDialogStyles.EDialogStyleWarning, title, prompt);

  return Observable.create(observer => {
    this.dialogWindow.observable.subscribe(buttonPressed => {
      const proceed = (buttonPressed === EButtonPressed.EButtonPressedYes);
      console.log('Allow proceed: ' + proceed);
      observer.next(proceed);
      observer.complete();
    });
  });
}