Pause and await for user input within an Angular function

I am facing an issue with my Angular function where I need to wait for a response from the user. I believe that using "subscribe()" might help, but I am unclear on how and when to use it properly. My current call 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;
}

}

Answer №1

Is it supposed to look like this?

When resolving the promise, we utilize await. In the case that it's an observable (which I assume it is), I employ lastValueFrom to transform it into a promise so that await functions correctly. If confirmDialog returns a promise, then using lastValueFrom is unnecessary!

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

To call the method:

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

Answer №2

Here is the revised code that has been corrected and now functions properly. I have implemented Angular with matDialog;

 var selectedResponse = await this.displayConfirmationDialogue("Discard Changes?", "Changes have been made to this account. Are you sure you want to discard them?");

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

const response = await lastValueFrom(
  this.dialog
    .confirmDialog({
      title: title,
      message: message,
      confirmCaption: 'Yes',
      cancelCaption: 'No',
    }));
console.log('selected response  ' + response)
return response;

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can a border be applied to a table created with React components?

I have been utilizing the following react component from https://www.npmjs.com/package/react-sticky-table Is there a method to incorporate a border around this component? const Row = require("react-sticky-table").Row; <Row style={{ border: 3, borderco ...

Error with 'Access-Control-Allow-Origin' while making a request using JavaScript

In the process of creating my angular 2 application, I've implemented a module known as github-trend. Within this setup, there is a service that interacts with various functions from the module. scraper.scrapeTrendingRepos("").then(function(repos) { ...

Is there any way I can verify the invocation of signOut in this Jest test case?

I am attempting to perform testing on my home page within a next app. However, I have encountered an issue with a button in the Home component that triggers a logout firebase function. Despite my attempts to mock this function and verify whether or not i ...

Splitting code is not being done through React's lazy import and the use of Webpack

//webpack development configuration const common = require("./webpack.common"); const merge = require("webpack-merge"); const globImporter = require('node-sass-glob-importer'); module.exports = merge(common, { mode: "development", modul ...

What steps should I take to fix this Angular 8 error?

Encountered an issue in ../node_modules/@angular/http/src/backends/jsonp_backend.d.ts:1:28 - error TS2307: Module 'rxjs/Observable' not found. 1 import { Observable } from 'rxjs/Observable'; ~~~~~~~~~ ...

Issue with Angular 2: The parent class dependency injection is not defined

I have been working on implementing a new service that all other services will extend in order to manage API responses. I came across this insightful discussion Inheritance and dependency injection and here is the parent class code snippet: import {Inje ...

Exploring the power of ContentChildren and ViewChildren in AngularElements with Angular 6 - a deep dive into

I have been experimenting with the new AngularElements feature which you can learn more about at https://angular.io/guide/elements. Initially, my tests were successful, but everything came to a halt when I integrated @ContentChildren. It makes sense to me ...

Utilize the async/await method when assigning a value to a global constant variable

I am facing an issue with declaring and initializing a const variable globally within a module. The variable needs to be assigned a value from an async/await function, but it keeps holding undefined. How can I rewrite this code to use a constant and have i ...

Having trouble locating variables in VueJS3 when using Axios and TypeScript?

I am facing an issue where I am unable to access the this.somethingHere variables inside methods using axios in combination with vuejs3 and TypeScript. Template code (not required): <template> <div> <form> <label for=" ...

I encountered an error in my Spring Boot application where I received a TypeError: Cannot read properties of undefined (reading '0') related to the angular.min.js file at line 129

As I work on designing a login page using Angular in my Java Spring Boot application, I encounter an issue. When attempting to log into the panel page, the username and password are successfully sent to the application via the API controller and the user t ...

Issue with login form in IONIC: Form only functions after page is refreshed

Encountering an issue with my Ionic login form where the submit button gets disabled due to invalid form even when it's not, or sometimes displays a console error stating form is invalid along with null inputs. This problem seems to have surfaced afte ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

I'm having trouble getting the [resetFilterOnHide]="true" functionality to work with primeng 5.2.7. Can anyone provide a solution for this issue?

I'm experiencing an issue with the p-dropdown component where the [resetFilterOnHide]="true" attribute isn't working as expected. When I type in the filter bar, close the dropdown by clicking outside of it, and then reopen it, the entered filter ...

Attempting to grasp the concept of Typescript generics

I have a function defined as follows: interface ExtraModels extends Model { unknown: string } const write = async (data: ExtraModels[]) => { console.log(data[0].unknown) } This function is currently working. However, I want to modify it to: cons ...

Best practices for implementing "Event Sourcing" in the NestJS CQRS recipe

I've been exploring the best practices for implementing "Event Sourcing" with the NestJS CQRS recipe (https://docs.nestjs.com/recipes/cqrs). After spending time delving into the features of NestJS, I have found it to be a fantastic framework overall. ...

Using conditional statements to localize in Angular

In my Angular application, I am utilizing i18n for internationalization purposes. When it comes to HTML, I use i18n="@@<unique_Id>" and for dynamic elements defined in TypeScript class files, I use $localize. For example: this.buttontext = ...

Angular and the collection of viewChild elements

I have come across this code snippet that is functioning quite well... import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'ionic-angular'; declare var google; @Component({ selector: &apo ...

TypeScript: Retrieve the data type of the provided object

Is there a way to create a function that receives a callback and returns the object returned by that callback? Here's an example of what I'm trying to achieve: const my_object = my_function<A extends string, B extends boolean> ("my_o ...

Steps for setting up i18nextStart by including the i

I am working on developing a multilingual app using the i18next package. Unfortunately, I am experiencing issues with the functionality of the package. Below is an example of the i18next file I have been using: import i18n from "i18next"; impor ...

From jQuery to Angular using Typescript

I have been trying to convert the following code snippets into Typescript, but haven't found a solution yet. Can you please advise me on how to achieve this functionality? $('html').addClass('abc'); $(".abc .wrap").css("height", h ...