Execute consecutive Angular2 functions in a sequential manner, one following the next

In my Angular2 project, I have a service that fetches data for dropdown menus on a form. However, when I call this service multiple times with different parameters in the form component initialization, only the last call seems to work, overriding the previous ones. It appears that subsequent calls are canceling out the previous fetches.

To tackle this issue, I separated each call into its own function. But now I need a way to execute these functions sequentially so that each one waits for the previous one to complete. Although each function works independently, calling more than one at a time causes errors as the current fetch is terminated when new parameters are passed.


this.fetchValueListOne();
this.fetchValueListTwo();
this.fetchValueListThree();

I initially tried using promises but ran into scoping problems while passing services and retrieving data. Each service call has three parameters and assigns data to a specific variable in the component used by the form.

Another attempt involved creating a list of functions as variables and iterating over them. However, similar scoping issues arose as with promises.

The service returns an Observable, which the functions subscribe to, retrieve data from, and assign to an array variable bound to a dropdown value list in the component.

Here is an example of how these functions look:


fetchValueListOne() {
    this.dataSvc.getValueList('Val-List-One', this.stateSvc.currentContext, this.stateSvc.currentLanguageCode)
        .map(response => response.json())
        .subscribe(
            data => {
                this.valListOne = data;
            },
            err => console.log('Error', err),
            () => {
                console.log('this.valListOne', this.valListOne);
            }
        );
}

Answer №1

After receiving guidance from SrAxi, I successfully tackled the issue by utilizing Promises as the most effective solution. In particular, implementing the Promise / .then mechanism proved to be the key in solving the problem.


  fetchValueList(listCode): Promise<any> {
      return this.dataSvc.getValueList(listCode, this.stateSvc.currentContext, this.stateSvc.currentLanguageCode)
          .map(response => response.json())
          .toPromise();
  }

  initializeDropDowns() {
      this.fetchValueList('First-Val-List')
          .then(data => {
              this.firstValList = data;
              return this.fetchValueList('Second-Val-List')
          }).then(data => {
              this.secondValList = data;
              return this.fetchValueList('Third-Val-List')
          }).then(data => {
              this.thirdValList = data;
          })  
  }

I declared these functions within the component and invoked initializeDropDowns() in ngOnInit.

The fetchValueList function returns a Promise. Therefore, upon calling it with the first listCode, the subsequent data is stored in the this.firstValList variable once the Promise resolves within the .then block. As each call returns data, we can safely proceed to make consecutive calls with different listCodes. The resulting data is then assigned to respective variables like this.secondValList.

This chaining process allows us to populate all necessary variables, terminating with an omission of the return statement in the final code block.

This scenario exemplifies a unique situation where a service must be called multiple times during component initialization, waiting for completion before proceeding. In such instances, utilizing the Promise / .then method proves to be exceptionally suitable.

Answer №2

Ensure the data is received before calling the functions, like so:

    this.getDataOne().subscribe((dataOne) => {
            this.getDataTwo(dataOne);
            // Process dataOne
        }
    );

    this.getDataTwo().subscribe((dataTwo) => {
            this.getDataThree(dataTwo);
            // Process dataTwo
        }
    );

    this.getDataThree().subscribe((dataThree) => {
            // Process dataThree
        }
    );

Make sure to declare these functions as Observable:

public getDataOne(): Observable<any> { // Get dataOne }
public getDataTwo(): Observable<any> { // Get dataTwo }
public getDataThree(): Observable<any> { // Get dataThree }

By following this structure, you can be confident that each function will have access to the required data.

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

`Angular application having trouble loading Azure Maps`

Hey there! I'm currently working on integrating Azure Maps into a basic Angular application. The error message I encountered is shown below. Any insights on why this might be happening and what steps can be taken to resolve it? atlas.min.js:2509 Err ...

Incorporate external JavaScript libraries not built with Angular

Our project utilizes NPM in conjunction with Browserify for managing third-party dependencies, which pairs well with AngularJS due to the CommonJS-modules. Below is a code snippet showcasing the dependency structure that integrates seamlessly with Angular ...

Live reload functionality in Webpack is currently not functioning as expected when utilized with the Angular

Recently purchased a template that incorporates Angular. I diligently followed all the initial setup steps, but encountered an issue with live reloading once I started making changes to the project. It is also worth noting that the project utilizes Webpa ...

Discrepancies in ESLint outcomes during React app development

As a newcomer to React development, I am encountering discrepancies between the errors and warnings identified in my project's development environment versus its production environment. Strangely, I have not configured any differences between these en ...

Steps for combining angular2-datatable with angularfire2 observable array:

Hey there! I am currently working on integrating angular2-datatable into my Angular 2 application. However, I have a query which is puzzling me: How can I transfer the array information from an angularfire2 observable to the data-table? Here is a screensho ...

After executing a query to a PostgreSQL database, I encountered an error preventing me from using res.send(). The error message stated: "Cannot set headers after they are sent to the client."

It may sound strange, but it's a true story. I was busy building an API on node.js when I encountered a peculiar error. As soon as the first res.status().send() was triggered during query processing, VS Code threw a "Cannot set headers after they are ...

Can you clarify the definition of component initialization in Angular 2+ specifically in relation to the OnInit lifecycle hook?

As per the Angular documentation on Life cycle hooks at Angular.io, the OnInit hook serves to initialize the directive/component after Angular has initially displayed its data-bound properties and set its input properties. But what exactly occurs when it& ...

Improving validation in Angular reactive forms by adding custom validation onBlur

I am struggling to correctly implement the OnBlur syntax for my project. export class AppComponent { form: FormGroup; constructor(private fb: FormBuilder) { this.form = this.fb.group({ published: true, credentials: this.fb.array([]), ...

`How can I manage my electron.js application effectively?`

As a newcomer to electron.js, I have successfully created a game using html, css, and javascript that currently runs offline on the client side. However, I am now looking for a way to access, analyze, and make changes to this app. One solution could be lo ...

socket.io / settings when establishing a connection

I'm facing an issue in my node.js / Express.js app where I need to pass parameters with the socket.io connection (saw a solution in another post). On the client side, here is a snippet of my code: edit var socket = io.connect('/image/change&ap ...

Dealing with an unexpected quantity of parameters in a jQuery.when.apply situation

Being new to programming in JavaScript, I am looking for a way to trigger multiple requests while preserving the order and ignoring any errors. After researching the documentation and code, I have come up with the following pattern: var requests = []; for ...

Combining union types with intersection operators in Typescript

Here's a concept for an event handling system: type EventMap = Record<string, any>; type EventKey<T extends EventMap> = string & keyof T; type EventReceiver<T> = (params: T) => void; interface Emitter<T extends EventMap&g ...

What is the best way to display and conceal a loader in order to reveal additional posts?

How can I display a loader when the user clicks on the "load more posts" button, show it while the posts are loading, and hide it once the posts have been successfully loaded? Additionally, I want to show the loader again when the user clicks on the button ...

What is the best way to test an AngularJS directive and monitor function calls with a spy?

After running the code below, an error is thrown mentioning that element.popover is not being invoked. I can't seem to identify what the problem is. Thank you in advance for any assistance provided. directive: angular.module('directives', ...

Use JQuery to locate and remove all commas within an unordered list, replacing them with empty spaces

Web Development <ul class="tabbox"> <li></li> , <li></li> , <li></li> </ul> Problem with JQuery Implementation $(".tabbox").replace(',' , ''); // I ...

Express fails to handle the POST request

Using ejs, express, nodeJS and mySQL has been great so far. However, I'm facing an error with this code: Cannot POST /search. I believe the index.ejs and app.js files are okay, but I suspect there's a problem with the searchRouter... app.js cons ...

One approach to animating elements on a web page is by utilizing Node.js

Imagine you want to programmatically define animated movement for elements on a web page. In JavaScript, this can be achieved using techniques outlined in this helpful guide: How TO - JavaScript HTML Animations. But how would you do this in Node.js? UPDAT ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...

I am looking to update the appearance of a button dynamically in Vue.js based on changes to an

Is there a way to toggle a visible button when the array changes? I'm having trouble implementing this. What is the most effective method? Check out my example below: https://codesandbox.io/s/relaxed-poincare-vv6xh?file=/src/components/HelloWorld.vu ...

Experiencing difficulties when attempting to launch a React application and Express/Node.js backend on a shared port

I'm trying to set up my react front-end on localhost:5000, with API requests going to localhost:5000/api/some-path. After looking at similar questions, I've come to understand the following: Include a proxy in the package.json file Serve st ...