Angular: Verify that all services are fully executed before proceeding to the next step

We have adopted Angular for our project. Our component receives data from an API, which is then processed by Data Services. These services transform the data by combining first and last names, rounding dollar amounts, performing calculations, etc. The final step involves populating the Sales year in a Dropdown menu after parsing all the information.

this.webStoreSearchHttpService.GetAllCustomerSalesData(this.customerId).subscribe((response) => {

  this.customerList = customerDataService.createCustomerList(response);
  this.productList = customerDataService.createProductAnalysis(response);
  this.salesList = customerDataService.createSalesList(response);
  this.salesYearList = customerDataService.createYearList(response);

  this.salesYearItemCurrent = _.cloneDeep(this.salesYearList[0]);   <--- this is used for a Mat Select Dropdown

However, the correlated data does not appear in the web dropdown selection because the Data Services are not finished parsing/creating yet, even though they are called within the original API subscribe function.

My goal is to ensure that all four Data Services are completely executed before populating the salesYear. Is there a way to achieve this using Angular typescript?

The Data Services can be executed in parallel, but the final step of populating the salesYear in the dropdown must follow.

Note that the methods return class arrays, not promises or observables.

Answer №1

Latest Update

Your input stated that the methods in the customerDataService return class arrays instead of promises or observables, suggesting that external waitability for asynchronous calls is limited. In this case, modifying the return value of the customerDataService methods is necessary as you aim to ensure completion of all 4 data services. It is presumed that these methods involve asynchronous tasks based on your statement, "What I am trying to do, is make sure all 4 Data services are totally complete."

Previous Version

In addressing your query, understanding the return type of the customerDataService methods is essential. Do these methods return a Promise or an Observable? Depending on this, one can employ either Promise.all or the forkJoin operator to await the completion of all methods before executing the select population. Below is an example utilizing observables:

this.webStoreSearchHttpService.GetAllCustomerSalesData(this.customerId).subscribe(response => {
    forkJoin([
        customerDataService.createCustomerList(response),
        customerDataService.createProductAnalysis(response),
        customerDataService.createSalesList(response),
        customerDataService.createYearList(response)
    ]).subscribe(([customerList, productList, salesList, salesYearList]) => {
        this.customerList = customerList;
        this.productList = productList;
        this.salesList = salesList;
        this.salesYearList = salesYearList;
        this.salesYearItemCurrent = _.cloneDeep(this.salesYearList[0]);
    });
});

To optimize and eliminate the nested subscription for better readability:

this.webStoreSearchHttpService.GetAllCustomerSalesData(this.customerId).pipe(
    flatMap(response => 
        forkJoin([
            customerDataService.createCustomerList(response),
            customerDataService.createProductAnalysis(response),
            customerDataService.createSalesList(response),
            customerDataService.createYearList(response)
        ])
    )
).subscribe(([customerList, productList, salesList, salesYearList]) => {
    this.customerList = customerList;
    this.productList = productList;
    this.salesList = salesList;
    this.salesYearList = salesYearList;
    this.salesYearItemCurrent = _.cloneDeep(this.salesYearList[0]);
});

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 11 error: Datatable type is not defined

We have a services.ts file that requires 2 arguments. UPDATE: It appears that I was looking at the error incorrectly. This method is causing the console error: private checkLink(row, options) { if (options.type === 'link' || options.type ...

No location matched any routes

I'm currently working on a notes application, and I've encountered an error when trying to edit the notes. The error message says "No routes matched location id ...". Any idea what could be causing this issue? The approach I'm taking is to ...

Struggling to create a TypeScript definition file - the JSX element 'SideMenu' lacks any construct or call signatures

I am currently working on creating a type definition file for react-native-side-menu in order to properly declare it. I have integrated it into a TypeScript project, but unfortunately, there are no TypeScript definitions available. Normally, my approach i ...

Make the current tab the active tab with the help of AngularJS

I have a set of five tabs that are functioning correctly. However, when I refresh the page, the active tab reverts back to its default state instead of staying in its current active state. Can anyone help me identify where I may be making a mistake? Here ...

I'm experimenting with using jQuery toggle to switch between text and images on my webpage

I attempted to use jquery "toggle" in order to hide the div containing text and display an image instead, and vice versa. However, when I click on the button, it does not work as expected. The button is from a bootstrap example - could that be the source o ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Following the update, Angular no longer requires any node dependencies

Recently upgraded from Angular 5 to 9 and encountered an error in the browser's devtools: Uncaught ReferenceError: global is not defined After researching, I found a helpful post that discusses the issue: Upgrading to angular-6.x gives "Unca ...

What is the most efficient and hygienic method for storing text content in JavaScript/DOM?

Typically, I encounter version 1 in most cases. However, some of the open source projects I am involved with utilize version 2, and I have also utilized version 3 previously. Does anyone have a more sophisticated solution that is possibly more scalable? V ...

Using assert along with exceptions in code can provide additional error handling capabilities

I recently began using Protractor in combination with Mocha and Chai. I've reached a point where I have performed some asserts like: const attributes = await TestingModal.getButtonAttributes(driver, myCss) assert.equal(attributes.text, 'Tes ...

What are some ways to implement AJAX with input from the user?

I'm currently working on a project to create a basic web page that will make use of AJAX for displaying results. Within main.py, I have a dictionary of words: words = { 'a': True, 'aah': True, 'aahed': True, ...

The absence of a React JS button on the page

I'm in the process of creating a React demo application and I've come across this component: var MediaList = React.createClass({ displayName: 'MediaList', getInitialState: function() { return { tweets: getTweets(numTweets) ...

Having trouble setting a background image for a specific DIV element in HTML

I am in the process of updating my webpage, and need some assistance implementing a small background image. Here is what I have done so far: https://i.sstatic.net/nTxtD.png Below is the marked section where I am trying to add the background image: https ...

Combine several elements in a single jQuery scrollreveal function

I am currently working on a webpage that utilizes the jQuery library plugin scrollreveal to gradually reveal different html elements when the page loads. The functionality of the code is working correctly at the moment, but I have noticed that there is a d ...

Creating a dynamic table based on selected dropdown option

I need to create a dynamic table of questions depending on the user's selection from a dropdown menu. When the user chooses a category, I want to pass that information to an API using the GET method. My controller is built using AngularJS. However, I ...

Error: Unable to access _rawValidators property of null object

I'm currently facing an issue with formgroup and formcontrol in Angular. When I run ng serve, it's showing an error in the console. Does anyone have a solution for this? TypeError: Cannot read properties of null (reading '_rawValidators&a ...

Streaming RTMP video through a WebView

Currently, I am working on implementing rtmp streaming using WebView. To achieve this, I referred to the code provided on Stack Overflow under this link The easiest way to play an audio RTMP stream in Android, which was shared by a user named Club. After a ...

Unlock the power of jQuery chaining with the val() method

My selected background color is set to: var _back = "#FF0000"; Why doesn't this code change the input field's background color: $("#input").val( _back ).css("background-color",$(this).val()); But this one does? $("#input").val( _back ) ...

Conditional Rendering with Next.js for Smaller Displays

I've implemented a custom hook to dynamically render different elements on the webpage depending on the screen size. However, I've noticed that there is a slight delay during rendering due to the useEffect hook. The conditionally rendered element ...

In Angular, the process of duplicating an array by value within a foreach function is not

I have been attempting to duplicate an array within another array and make modifications as needed. this.question?.labels.forEach((element) => { element["options"] = [...this.question?.options]; // I've tried json.stringify() as wel ...

What is the best way to send a list of data as either strings or integers through a REST API using Angular's

While trying to post data from Angular formData to a Django REST API, I encountered an error saying "Incorrect type. Expected pk value, received str." Here is how I am currently sending the data using form data: let noticeData = this.announceForm.value; i ...