Executing another function after an asynchronous function in Angular

After running the search() function, I want the toggle() function to execute. However, the this.toggle(element) function is not being performed after this.search().

addElement(element) {
  element.isExpanded = !element.isExpanded;
  const dialogRef = this.dialog.open(DialogBoxComponent, {
    width: '300px',
    data: element
  });
  dialogRef.afterClosed().subscribe(async result => {
    if (result==true) {
      await this.search();
      this.toggle(element);
    }
  });
}

public search() {
this.productService.findByLabel(this.label)
.subscribe(
  res=> {
    this. dataSourceProduct.data = res as Product[];
  },
  (error) => {
    this.errorService.handleError(error);
  })
}

toggle(element) {
  let elements = this.dataSourceProduct.data.filter(x => x.id ===   element.id);
  elements.forEach((element: any) => {
  element.isExpanded = true;
  });
}

Answer №1

To accomplish this task, you can utilize the Promise feature.

>   public search() {
> 
>     return new Promise((resolve, reject) => {
>       this.productService.findByLabel(this.label).subscribe(res => {
>         this.dataSourceProduct.data = res as Product[];
>         resolve()
>       }, (error) => {
>         this.errorService.handleError(error);
>         reject()
>       })
>     })   
}
  • Implement the search function in the following manner

    this.search().then(res => { //toggle function }, reject => { //error} )}

Answer №2

Here is a simple way to achieve this:

updateElementStatus(element) {
  element.isExpanded = !element.isExpanded;
  const dialogRef = this.dialog.open(DialogBoxComponent, {
    width: '300px',
    data: element
  });
  dialogRef.afterClosed().subscribe(result => {
    if (result == true) {
      this.refreshData().then(() => {
        this.switchState(element);
      }).catch((error) => console.error);
    }
  });
}

Answer №3

Once search() is called, the product list appears. However, the next step should involve executing the toggle(element) function, which is currently not happening - only the product list is being displayed.

  public search() {
    this.productService.findByLabel(this.label)
    .subscribe(
      res=> {
        this.dataSourceProduct.data = res as Product[];
      },
      (error) => {
        this.errorService.handleError(error);
      })
  }

Answer №4

Can you explain the output of this.search() ? It is expected to return either a promise or an observable in order to signal your code when the function completes, allowing for the execution of the next line.

If opting for an observable, remember to employ subscribe rather than await. Alternatively, with promises, you can utilize .then

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

Display real-time information in angular material table segment by segment

I need to incorporate service data into an Angular mat table with specific conditions as outlined below: If the difference between the start date and end date is less than 21 days, display 'dd/mm' between the 'start_date' and 'end ...

tslint is flagging an error related to cyclomatic complexity

Within my Angular 8 project, the following dependencies are utilized: "codelyzer": "^5.1.0", "ts-node": "~8.3.0", "tslint": "~5.19.0", Upon executing: ng lint myapp --fix=true An error is raised stating: ERROR: ...html:428:106 - The cyclomatic complex ...

What causes the component's constructor to be invoked multiple times instead of being efficiently reused by the router?

I came across this interesting article where the writer discusses how the router reuses components to avoid unnecessary DOM modifications: In order to prevent unnecessary changes to the DOM, the router will reuse components when the parameters of the co ...

How to specify in TypeScript that if one key is present, another key must also be present, without redundantly reproducing the entire structure

In my code, I have a custom type defined like this (but it's not working): type MyType = | { foo: string; } | { foo: string; barPre: string; barPost: string; } | { foo: string; quxPre: string; qu ...

Tips for preventing VSCode TypeScript files from importing from unauthorized folders?

We work with typescript and webpack in a single repository to develop our game. To ensure shared states and objects, we have organized the code into three main folders. This shared code is utilized on both the backend and frontend. It is crucial that serv ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...

When implementing useReducer with TypeScript, the error "Argument of type '(type, action) => { state: (...}' is not assignable to parameter of type 'ReducerWithoutAction<any>'" may occur

Recently, I decided to delve into learning TypeScript by building a simple shopping cart application. If you want to check out the code, feel free to visit my GitHub repository: https://github.com/CsarGomez/shopping-cart-reducers-tx I've encountered ...

There appears to be an issue with the dynamic functionality of RouterLink in Angular 6

user-dashboard.html <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link" routerLink='/dashboard'>User Dashboard</a> </li> <li class="nav-item" *ngFor="let cat of categories; let i = in ...

How can I display a sessionStorage string in an Angular 8 HTML view?

I'm looking to show the data stored in sessionStorage on my angular view. This is my current session storage: sessionStorage.getItem('username'); In my dashboard.ts file, I have: export class DashboardComponent implements OnInit { curr ...

Angular Test Error: Refactoring requires a source file to be present

Trying to execute the command ng test, I encountered an error message. How can this issue be resolved? I am unsure of its meaning. ERROR in Must have a source file to refactor. To eliminate this warning, use "ng config -g cli.warnings.versionMismatc ...

Using Rust WebAssembly in Next.js

Seeking assistance with integrating a rust-generated wasm module into my NextJS project. This is how I am attempting to import the wasm: import init, { tokenize } from "@/wasm/lazyjson"; const Test = dynamic({ loader: async () => { ...

Refreshing an Angular page with parameterized routes on IIS results in a blank page

In an effort to resolve the 404 error that occurs when refreshing a page on my Angular application, I made modifications to the web.config file within the website folder on IIS. The code snippet added is shown below: <rule name="AngularJS Routes&qu ...

The AngularJS Cross-Origin Resource Sharing (CORS) Policy

Our team is currently working on a web application using AngularJS that requires calling REST API services from another application. However, due to it being a cross domain request, we are facing difficulties in making the calls and receiving the following ...

Retrieving source in Angular from an async function output within a specified time limit

I have a quick query :). I'm attempting to retrieve the image src from an async function, but so far, I haven't had much success. This is what I have: <img [src]="getProductImage(articleNumber)"/> and in my TypeScript file: publi ...

Express application (utilizing TypeScript) failing to handle routes efficiently

Encountering a technical issue : I am developing a REST API, but my application does not seem to trigger the actions when I send a request to the endpoint. This is my server configuration: import express, { Express } from 'express'; import c ...

The error message "Subscription is not a valid function" is displayed

I'm attempting to subscribe to an observable from a service. The code builds successfully, but I encounter the error "this.service.getBanners(...).subscribe is not a function" when I try to view it in the browser. Service: import { Injectable } from ...

I am unable to see any elements showing color in the print preview

Currently using angular 4 and in need of a feature that allows the user to print a specific section of data. Although I have successfully implemented a bootstrap print preview, the issue arises when no colors are displayed in the preview. This problem pers ...

Vue3 and TypeScript encounter a problem where the attribute 'dataToggle' is not recognized on the type 'ElementAttrs<AnchorHTMLAttributes>'

Query In my vue 3 application, I am facing an issue while trying to implement a bootstrap4 snippet for creating a nav bar menu - <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#&quo ...

Incorporate the Authy library from Twilio into a NestJS project

When working with the authy library in a Node.js file using JavaScript, we typically use the following statement: const authy = require('authy')('API KEY'); Now that I have moved my code to the Nest ecosystem and am using TypeScript, h ...

What is causing my method chain to return a Promise<Promise<boolean?>> when using browser.wait(ExpectedConditions.presenceOf())?

Currently, I am in the process of creating some protractor tests that look like this: import { browser, element, by, ExpectedConditions } from 'protractor'; export class SomePage { private elements: any = {}; navigateToUpdate(name: string) ...