Ionic不会更新视图中的变量

时间:2018-10-31 19:54:26

标签: angular ionic-framework ionic4

我对 Ionic 4 有疑问,为什么 Angula r不使用新的警报控制器实时更新视图。

例如,我有一个简单的倒计时代码,完成后,在模式警告中单击“确定”后,计时器将再次启动。

我在 controller 中拥有此代码:

   outputRemainingTime: string;
    secondsRemaining:  number = 60;

    initTimer() {
      this.timerTick();
    }

    timerTick() {
    //this.ngZone.run(() => {
      this.timerInterval = setTimeout(() => {
         if (this.isPause) { return; }
           this.secondsRemaining--;
           this.outputRemainingTime = this.getSecondsAsDigitalClock(this.secondsRemaining);
           if (this.secondsRemaining > 0) {
               this.timerTick();
            } else {
               this.onFinishSession();
            }
          }, 1000);
       //})
     }

    getSecondsAsDigitalClock(inputSeconds: any) {
      const secNum = parseInt(inputSeconds.toString(), 10); // don't forget the second param
      const hours = Math.floor(secNum / 3600);
      const minutes = Math.floor((secNum - (hours * 3600)) / 60);
      const seconds = secNum - (hours * 3600) - (minutes * 60);
      let minutesString = '';
      let secondsString = '';
      minutesString = (minutes < 10) ? '0' + minutes : minutes.toString();
      secondsString = (seconds < 10) ? '0' + seconds : seconds.toString();
      return minutesString + ':' + secondsString;
    }

    onFinishSession() {
      showAlert()
    }

  async showAlert() {
    const alert = await this.alertCtrl.create({
      header: "Header Title",
      message: "Messaggio",
      buttons: [
        {
          text: 'Ok',
          handler: () => {
            this.secondsRemaining = 5;
            this.initTimer();  
          }
        }
      ]
    });
    await alert.present();
  }

以及视图中的以下代码:

<ion-header>
  <ion-toolbar>
    <ion-title>timer</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
    {{ outputRemainingTime }}
</ion-content>

问题是新的异步alertController,如果替换我的警报功能,则此代码并查看工作

showAlert() {
    this.secondsRemaining = 5;
    this.initTimer()
}

1 个答案:

答案 0 :(得分:0)

尝试改用onDidDismiss或onWillDismiss:

alert.onDidDismiss().then(() => {
  // make model changes here
});

使用您的示例:

async showAlert() {
  let resetTimer = false;

  const alert = await this.alertCtrl.create({
    header: "Header Title",
    message: "Messaggio",
    buttons: [
      {
        text: 'Cancel'
      },
      {
        text: 'Ok',
        handler: () => {
          resetTimer = true;
        }
      }
    ]
  });

  alert.onDidDismiss().then(() => {
    if (resetTimer) {
      this.secondsRemaining = 5;
      this.initTimer();
    }
  });

  await alert.present();
}

Angular无法检测到从同步调用到AlertInput处理程序函数的更改可能是Ionic的错误,但是可以说上述解决方法对于异步编程而言可能是更好的形式。