Wait for user input in Angular function

53 views Asked by At

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;
}

}

2

There are 2 answers

1
Naren Murali On BEST ANSWER

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?");
0
Graham On

Below is the Corrected coding that now works. I am using Angular with matDialog;

 var selectedAnswer = await this.showConfirmDialog("Abandon Changes?", "You have made changes to this account.  Are you sure you want to abandon them?");

  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;

}