angulartypescriptasync-awaitsubscribe

Wait for user input in Angular function


I have a function in Angular where I need to wait for a response from the user, but I am not having any success. I THINK I should be using "subscribe()" but don't fully understand how and when to use it. My call currently looks like this:

theAnswer:boolean = await showConfirmDialog("Confirm Changes!", "Are you sure you want to cancel your changes?);

    async showConfirmDialog(title: string, message: string) {

var answer: boolean = false;

  this.dialog
  .confirmDialog({
    title: title,
    message: message,
    confirmCaption: 'Yes',
    cancelCaption: 'No'
  })
  .subscribe((yes) => {
    if (yes) {
      answer = true;
    }
    else {
      answer = false;
    };
  });

  console.log('selected answer ' + answer)
  return answer;
}

}


Solution

  • Shouldn't it be like below?

    We use await to resolve the promise, if its a observable which I am assuming it is, I use lastValueFrom to convert it to a promise so that await will work, if confirmDialog returns a promise then there is no need for lastValueFrom!

    import { lastValueFrom } from 'rxjs';
    ....
    async showConfirmDialog(title: string, message: string) {
      const answer = await lastValueFrom(this.dialog
        .confirmDialog({
          title: title,
          message: message,
          confirmCaption: 'Yes',
          cancelCaption: 'No'
        }))
      console.log('selected answer ' + answer)
      return answer;
    }
    ...
    

    Calling the method will be like

    const theAnswer: boolean = showConfirmDialog("Confirm Changes!", "Are you sure you want to cancel your changes?");