The table fails to populate data effectively when making multiple AJAX requests

One of the columns in my table is populated by a separate AJAX call after all the other columns have been filled. However, I am facing issues with the data not always displaying correctly due to the timing of this second call. I'm looking for advice on how to resolve this issue effectively. Below is the relevant code:

HTML:

<tr ng-repeat=“item in ctrl.items">
  <td>{{ item.name }}</td>
  <td>{{ item.desc }}</td>
  <td><i class=“icon icon-check”></i> ng-class=“{ ‘active': ctrl.isActive(item) }”></td>
</tr>

CONTROLLER:

loadItems() {
  myService.getItems().then( (response) => {
       this.items = response;
       this.loadColors();
  });
}

loadColors() {
  myService.getColors().then( (response) => {
     _.forEach(response, (val, key) => {
          _.forEach(this.items, function(item) {
               if (item.id === key) {
                    item.colors = val;
               }
          });
     });
  });
}

isActive(item) {
    return _.some(item.colors, function (color) {
        return color === ‘green’ || color === ‘blue';
    });
}

The issue I'm facing is that the 'active' css class in the last column does not get applied consistently. It sometimes works after reloading the page, but not always. I have tried using $timeout and $scope.$apply around this.loadColors(), but it hasn't resolved the problem.

Answer №1

When your output relies on the results of two separate calls, it's important to chain them together in order to receive the final result once both operations are complete.

loadItems() {
  myService.getItems().then( (response) => {
       this.items = response;
       myService.getColors().then( (colorResponse) => {
     _.forEach(colorResponse, (val, key) => {
          _.forEach(this.items, function(item) {
               if (item.id === key) {
                    item.colors = val;
               }
          });
     });
  });
  });
}

This method should resolve the issue at hand.

UPDATE I've made adjustments to my code, specifically addressing the timing of assigning items. In the revised version, I've moved this operation to the final step.

loadItems() {
      myService.getItems().then( (response) => {
           var items = response;
           myService.getColors().then( (colorResponse) => {
         _.forEach(colorResponse, (val, key) => {
              _.forEach(items, function(item) {
                   if (item.id === key) {
                        item.colors = val;
                   }
              });
         });
         this.items = items; //Assigning it to items after setting the colors.
      });
      });
    }

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

The Node gracefully disconnects and apologizes: "I'm sorry, but I can't set headers after they have already

events.js:160 throw er; // Unhandled 'error' event ^ Error: Can't set headers after they are sent. register.js:20:18 register.js user.save(function(err) { if(err){ return mainFunctions.sendError(res, req, err, 500, ...

Strategies for making recursive calls to an API in the event of an expired access token in React Next.js without relying

Currently, I am in the process of constructing the client page using Next.js. To achieve this, I have implemented a function called handleSubmit that triggers an API call to generate a new product each time a user interacts with a designated button. Within ...

Manipulating Strings in JavaScript

Hi there, I'm a beginner in JavaScript and I could really use some help with the following question. So, let's say I have this string: "AB_CD.1.23.3-609.7.8.EF_HI.XBXB" The numbers 1.23.3 and 609.7.8 are completely random with two dots separat ...

What is the best way to trigger the opening of a Component upon an onPress event?

One challenge I am facing is implementing a button in my app's Screen that should open a self-made Modal component on the same screen. To achieve this, I have set up a visible state in the screen and created an onPress handler for the button to toggl ...

Tips for creating flexbox children that adjust their height to match the first child, even when it has varying heights

Imagine a flexbox with 3 elements: The first child contains 4-7 lines. The second child contains 40-50 lines. The third child contains 2-5 lines. My goal is to make the height of the second child match that of the first child. I am aware that I could se ...

$stateChangeStart - Transition not stopped

When a user attempts to access a restricted state without proper authorization, the restricted state loads briefly before being redirected back by $state.go(fromState.name). It appears that the event.preventDefault(); is not functioning as expected. $r ...

Obtain the RxJS bundle directly from unpkg

Currently, I am working on an Angular 2.0.0 project (facing the same issue in 2.2.0) where the development build is generating over a hundred HTTP requests. The reason for this excessive number of requests is because it is loading non-bundled versions of ...

Ways to have Express backend redirect you following a successful submission of a request via the Fetch API from the frontend?

Behold the following code snippet which illustrates the typical backend sign-in logic. If the user's credentials are correct, they will be redirected to the admin panel: import Express from "express"; import { Controller, Post, Body as Reque ...

Exploring JS Object Property Access and Iteration with an Illustrative Example

Something strange is happening... the code snippet below generates a table displaying a list of SNMP object/values from any OID provided for walking. Strangely, the variable 'jason' is not behaving as expected. Initially, I am unable to access t ...

Troubleshooting problem: Unable to restrict table selections - issue with Material UI table in React

I seem to be overlooking the simple solution here. Currently, I have a ternary on my table. If the length of the selected array is greater than a certain number, a table with disabled checkboxes is rendered. I also implement a different handleClick functio ...

The CSS gradient is not displaying properly, and the footer is not staying at the bottom of the page and is not resizing correctly on mobile devices

Does anyone know how to make this code responsive for mobile and other devices? Visit: Issues: The gradient text doesn't load correctly when resizing the website. The footer doesn't stick to the bottom and has display errors on mobile. The H ...

Navigate through photos (jQuery) to adjust size and location dynamically (CSS)

Currently, I am in the process of developing a jQuery script that will automatically adjust the size and position of image elements upon page load or resize. To structure my layout, I am utilizing Bootstrap and have set a fixed height using CSS. It is wort ...

Employing AJAX to utilize keyboard arrow keys for selecting elements in an autocomplete feature

I am currently working on creating an autocomplete search box using a combination of Ajax, PHP, and jQuery. While I have successfully implemented the ability to select items from the search results using a mouse, I am now looking to enhance the functional ...

Encasing the letter "Y" within a span tag will result in a wider margin between it and the following character

I'm currently working on a project that requires wrapping each character of a sentence in a span element. This is necessary so I can accurately measure the distance from the beginning of the sentence to each individual character. However, I've e ...

Facing issue with AngularJS ng-model not accepting input values

Could you please review this code snippet? I am attempting to retrieve the value from the UI but it is returning as undefined. Here is the relevant code snippet: Upon checking in the console, the value appears as 'undefined'. UI Code - <tab ...

Navigating the dynamic components in Vue using dynamic routing

I'm currently developing an application that helps users manage maintenance tasks. I have successfully created a component to display all the data stored in an array of objects. However, I am facing a challenge in redirecting users to different pages ...

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...

Guide on declaring package.json during library publication in Angular 6

Building node modules using Angular6 should be a breeze. The Documentation outlines the following steps: ng generate library YOUR-LIBRARY ng build YOUR-LIBRARY --prod cd dist/YOUR-LIBRARY && npm publish By following these steps, a new project wi ...

Learn how to resolve the issue of "Property 'item' does not exist on type 'never'." in Angular using TypeScript with the following code snippet

addToCart (event: any) { if ("cart" in localStorage) { this.cartProducts = JSON.parse(localStorage.getItem("cart")!) console.log(event); let exist = this.cartProducts.find(item => item.item.id == event.item.id); ...

Guide to sending both image and text data using multipart form in AngularJS and Spring MVC

I have been experimenting with code in AngularJS to append text and file values to form data and send it to the controller. However, when I submit the form, I encounter a 415 unsupported content type error https://i.sstatic.net/V9VUb.png in my console. &l ...