Invoke a function once a series of functions have finished executing in Angular 8

As a beginner in Angular, I am facing a challenge in calling a function after a series of functions have completed their execution. Although I don't require these functions to run sequentially, I do need to trigger another function once all of these functions have finished running.

Here is the snippet of code I am working with:

  global() {
    this.productsService.getProducts().subscribe(res => {
      this.products = res;

      this.products.forEach((product, index) => {
        this.fullProductDetails[index] = new FullProduct();
        this.fullProductDetails[index].product = product;

        this.f1(product['a'], index);
        this.f2(product['b'], index);
        this.f3(product['c'], index);
      });

      this.initProductsChart();
    });
  }

  f1(a: any, index: number) {
    this.productsService.getSomethingByA(a).subscribe(res => {
      this.fullProductDetails[index].somethingA = res;
    });
  }

  f2(b: any, index: number) {
    this.productsService.getSomethingByB(b).subscribe(res => {
      this.fullProductDetails[index].somethingB = res;
    });
  }

  f3(c: any, index: number) {
    this.productsService.getSomethingByC(c).subscribe(res => {
      this.fullProductDetails[index].somethingC = res;
    });
  }

  initProductsChart() {
    ...
  }

My goal is to kick off the initProductsChart() function only after all instances of f1(), f2(), and f3() have been completed for each product.

Is there a way to achieve this, or do I have to wait for each individual function to finish executing?

Answer №1

If you want to fetch data from multiple sources simultaneously, you can leverage forkJoin from the rxjs library.

    activeRequests = [];
    fetchData() {
    this.dataService.getData().subscribe(response => {
    this.data = response;

    this.data.forEach( (item, index) => {
        this.fullDataDetails[index] = new FullData();
        this.fullDataDetails[index].data = item;

        this.activeRequests.push(this.fetchAData(item['a'], index));
        this.activeRequests.push(this.fetchBData(item['b'], index));
        this.activeRequests.push(this.fetchCData(item['c'], index));
    });
    forkJoin(this.activeRequests).subscribe(() => {
        this.processData();
    });

    });
}

fetchAData(a: any, index: number) {
    this.dataService.getAData(a).subscribe(response => {
    this.fullDataDetails[index].aData = response;
    });
}

fetchBData(b: any, index: number) {
    this.dataService.getBData(b).subscribe(response => {
    this.fullDataDetails[index].bData = response;
    });
}

fetchCData(c: any, index: number) {
    this.dataService.getCData(c).subscribe(response => {
    this.fullDataDetails[index].cData = response;
    });
}

processData() {
    ...
}

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

Adding SVG to Component

I am attempting to embed an SVG element (retrieved using http.get()) into a 'icon' component. export class BgIcon { private svgSrc_: string; icon_: Icon; @Input('svg-src') set svgSrc(value: string) { this.svgSrc_ = value; ...

Pass data between different parts of the system

Utilizing the angular material paginator has been a great experience for me. You can check it out here: https://material.angular.io/components/paginator/examples. The paginator triggers an event which allows me to print the page size and page index. This f ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

Page Breaks - Patience in anticipation of dataSource readiness

I am facing an issue with my pagination service and component. The dataSource appears empty when the page is loaded for the first time, but by the second time it is populated and I can display the dataTable and paginate successfully. Is there a workaround ...

Accessing a JSON value in SCSS for localization

I have a JSON file containing all the values that I want to use for internalization in my app. On the HTML side, I am able to retrieve the values, but on the CSS side, I am using a "before" pseudo-element. In my HTML, I am using the class "menu-input" li ...

Attempting to launch Angular application on GitHub Pages

I need help deploying my Angular application on GitHub pages using node.js 14.20.0. I've successfully installed: npm i angular-cli-ghpages However, when I try to run : ng deploy --base-href=https://rejkid.com.github.io/ScheduleMeFrontEnd/ as recomme ...

Challenges arise when working with multiple promises while attempting to retrieve download URLs from Cloud Storage

My goal is to save each downloadURL from multiple promises (files being uploaded) in an array while iterating through them. However, what's happening is that I only get the first output for every item, regardless of how many items I upload. It keeps g ...

mongodb is experiencing issues with the findOneAndUpdate operation

Below is the code snippet for updating the database. let profileUrl = 'example' UserSchemaModel.findOneAndUpdate({_id:userId}, {$set: {profileUrl:profileUrl} }, {new:true}) .then((updatedUser:UserModel) => { console.log(updatedUser.profil ...

Is there a way to alter the stroke color of an SVG icon in Angular 2 or 4 by clicking on it?

Having trouble with this code, can someone provide a solution? This is the SVG icon code: <svg id="Home" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52.28 43.49"> <defs> <style> .cls-1{fill:none;stro ...

How to dynamically add a component in Angular 7/8 when a button is clicked

I am facing an issue with importing a common component when a button is clicked. The component contains standard HTML elements which can be viewed on Stackblitz However, upon clicking the button, an error is thrown: Error: Cannot read property 'c ...

Exploring the World of Micro-Frontends with the Angular Framework

I am conducting research on the best methods for transitioning a large single-page application into a micro-frontend architecture. The concept: The page is made up of multiple components that function independently Each component is overseen by its own ...

Expanding a TypeScript interface across different modules

For my project, I am working with Highcharts typings and encountered a need to extend certain object/interfaces it defines by adding some custom properties. Here is an example: declare namespace Chart { interface ChartOptions extends Highcharts.ChartOpt ...

There are no specifications available for the project that is located in the same workspace as the main

I have been given the responsibility of testing an application for a company. When I execute the main project using "ng test", it runs smoothly and detects all its test suites. However, when I attempt to run another project within the same workspace named ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Filtering an array of objects based on a specific condition in TypeScript

I am trying to filter the array object data where the count of Failed is greater than 0. Unfortunately, the code below is not working as expected. ngOnInit() { this.employeeService.getProducts().subscribe((data:any) => { console.log(data); this. ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

Is there a way to optimize app speed in Angular2 by importing CommonModule and RouterModule in a centralized location?

I find myself constantly importing these two modules in almost every component: import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; Is there a way to import them only once in the global app. ...

Examining React components with Enzyme for event usage in components

Struggling with testing react components that utilize event.target in events has been a challenge for me. Take for example the component code snippet below; import * as React from 'react'; import { generateGuid } from '../../../utilities/Gu ...

Having trouble retrieving a value from the img.onload event handler. A 'boolean' type error is being thrown, indicating it cannot be assigned to type '(this: GlobalEventHandlers, ev: Event) => any'

In my Angular application, I have implemented a method that verifies the size and dimensions of an image file and returns either false or true based on the validation result. Below is the code snippet for this function: checkFileValidity(file: any, multipl ...

Integrating a local library with Angular: A comprehensive guide

As I was developing an Angular application, I had the idea to create a library containing reusable components for future projects. To achieve this, I set up a separate Angular workspace where I created a library project. I utilized the automatically genera ...