Utilize data from two distinct JSON sources that are updated at varying intervals, and display the combined results in an ng-repeat

I am currently working on creating a status list that pulls data from two separate JSON sources. The main purpose of this list is to show general information from the first source, while also indicating a status color based on the number of people in the second source.

The first JSON source contains static data such as feed name, version, and description, which will only be updated twice a day. Here is an example of the code:

/metadata

{
    data: [
        {
            "feedName": "Feed 1", 
            "version": "000001", 
            "location": "1234 Main Street, New York, New York" 
            "description": "This feed provides information about the number of individuals in Building A at any given time."
        }, 
        {
            "feedName": "Feed 2", 
            "version": "000001", 
            "location": "1000 Broad Street, New York, New York" 
            "description": "This feed provides information about the number of individuals in Building B at any given time."
        }, 
        {
            "feedName": "Feed 3", 
            "version": "000001", 
            "location": "1111 Governor Street, New York, New York" 
            "description": "This feed provides information about the number of individuals in Building C at any given time."
        }
    ]
} 

The second JSON source contains dynamic data for each feed that changes frequently and needs to be updated every hour.

/customers

{
    data: [
        {
            "metricName": "Feed 1", 
            "customerNumber": "10", 
            "time": "2012-10-03 15:30:00"

        }, 
        {
            "metricName": "Feed 2", 
            "customerNumber": "5", 
            "time": "2012-10-03 15:30:00"
        }, 
        {
            "metricName": "Feed 3", 
            "customerNumber": "15", 
            "time": "2012-10-03 15:30:00"
        }
    ]
} 

Where both metricName and feedName have the same values.

In previous cases, I have only worked with one JSON source per list. However, now I need to figure out how to make asynchronous calls to each data source and then match up the data to populate my list with information from both metadata and customers.

Update I did try using

ng-repeat = "data in metadata.concat(customers)"
approach as referenced in this Stack Overflow thread, but it didn't provide the desired result. It simply appended the data to the end of the list.

Any suggestions or guidance on this matter would be greatly appreciated. Thank you!

Answer №1

To begin, utilize the all() method from the $q service to handle multiple promises concurrently, such as in the case of two requests.

// Fetching JSON data using two promises
var promises = {
  metadataPromise: $http.get('/echo/json/', {}),
  customersPromise: $http.get('/echo/json/', {})
};

$q.all(promises).then(function(response) {
  metadata = response.metadataPromise;
  customers = response.customersPromise;

  mergeMetadataAndCustomers();
}, function(response) {
  // Handle promise rejection here
});

Next, iterate through each feedName and find the corresponding metricName by utilizing the filter function. Finally, merge the two datasets together using angular.merge.

var mergeMetadataAndCustomers = function() {
  metadata.data.forEach(function(mtd) {
    customers.data.filter(function(customer) {
      return customer.metricName === mtd.feedName;
    }).forEach(function(customer) {
      $ctrl.metadataAndCustomers.push(angular.merge({}, mtd, customer));
    });
  });
}

This approach may not be optimal for all scenarios but it gets the job done. You can always refine it based on your specific requirements. For instance, if there is only one matching record, you can skip the last forEach loop.

Check out this example on JSFiddle: https://jsfiddle.net/virgilioafonsojr/tv1ujet0/

I trust this information proves valuable.

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

Refreshing a section of a webpage using AJAX and PHP

After creating a RESTful API in PHP, I can easily register information by accessing the address . This registration process involves sending a POST request. Below is an overview of my method: File: api.php <?php /* File: api.php */ private function ...

Generate unique identifiers to rotate images dynamically on the webpage

My goal is to rotate every image on a page, and while this works with a single image, it only rotates the first one since each ID needs to be unique. I need to find a way to dynamically increment the IDs as they are encountered on the page. Below is what I ...

Use TypeScript to cast the retrieved object from the local storage

const [savedHistory, setSavedHistory] = useState(localStorage.getItem('history') || {}); I'm facing an issue in TypeScript where it doesn't recognize the type of 'history' once I fetch it from localStorage. How can I reassign ...

Editable dropdown in Angular - customize editability according to selected option

UPDATE 1: I have created the initial sample code as a foundation for proper implementation. UPDATE 2: Successfully developed a functional model. Please refer to the answers. During my research, I came across this library: This library enables the addit ...

What exactly does the symbol "++" signify in the context of jQuery and JavaScript

Throughout my observations, I have noticed people employing i++, especially within a for-loop. However, the specific purpose of ++ when used with a variable remains unclear to me. My attempts to locate documentation explaining its function have been unsuc ...

Choosing an option from a dropdown menu in Google Forms using Puppeteer in NodeJS

Hey everyone, I've been working on automating a Google form and I'm facing an issue with a dropdown menu. I'm struggling to select the desired value from the dropdown list. When I use Puppeteer to type in "United space Kingdom," it autocomp ...

Combining Strings in Angular

Looking for a simple solution but struggling to find one. CSS <div class="col-md-4"> <input type="text" class="form-control" placeholder="name" ng-model="main.name" ng-change="updateData()"> </div> <div class="col-md-8"> <inpu ...

Issue encountered with the latest version of Selenium web driver when using Firefox browser

I am currently using Selenium jar version 3.3.1 with Firefox 43.0.4 and Eclipse Mars.2 Release (4.5.2). When I execute the following code: import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selen ...

Only send the parameter for variables that are not empty in the AJAX data

How can I pass the variables that are not empty in the data object for an AJAX request? In this scenario, the area variable is empty so I need to pass parameters for city and listing type instead. Can someone please help me figure out how to do this? va ...

Getting rid of a texture in three.js

I am attempting to deallocate a texture once it has been loaded in three.js. The texture is loaded using var tex = THREE.ImageUtils.loadTexture("image.png"); and it is being displayed correctly. However, when I attempt to use: tex.dispose(); I consist ...

I'm struggling to concentrate and unable to type in the email field

Today while working on a website, I encountered something strange. In the footer section of the site, there is a quick contact form. However, I noticed that in Firefox, I am unable to focus on the email field. Surprisingly, this issue does not occur in Chr ...

Obtaining JSON data in Android's splash screen view

In my attempt to develop an app, I encountered an issue. The app should first display a home page for 2 seconds. Below is the code snippet... public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { ...

Uploading images seamlessly through ajax

Despite the abundance of tutorials, I am struggling to make them work. In my input form for file upload, I have: <input onChange="userPreviewImage(this)" type="file" accept="image/*" style="display:none"/> Here is my Javascript code: function use ...

Converting Json string containing escape characters into a valid json format on Android

Trying to parse a JSON response from a REST call has been difficult due to the presence of escape characters such as "\n". Even replacing "\" with "" did not yield the desired results. "[{\"message_id\":50870,\"message\":&bso ...

It appears that the Angular 2 HTTP header is being produced or transmitted erroneously

Trying to send a request to my backend that uses HTTP Basic authentication for testing purposes. username: user password: password The correct header should be: Authorization: Basic dXNlcjpwYXNzd29yZA== Request tested with this header in Chrome Advance ...

Python web scraping: Extracting data from HTML tag names

Seeking help with extracting user data from a website by retrieving User IDs directly from tag names. I am utilizing python selenium and beautiful soup to extract the UID specifically from the div tag. For instance: <"div id="UID_**60CE07D6DF5C02A987E ...

Encountering an issue with Angular build in Docker: [ERR_STREAM_DESTROYED] - Write function cannot be called after a stream

Below is the docker file I'm using to build my Angular project: FROM node:12-buster-slim as build-step RUN mkdir -p /app COPY . /app WORKDIR /app RUN chmod 777 -R /app RUN npm install ARG configuration=production RUN npm run build -- --output-path=./ ...

What is the best way to create a smooth sliding effect using CSS?

Need help with creating a transition effect within a bordered div that reveals hidden content when a button is clicked? I'm looking to have the <a> tag displayed after clicking the button, with both the button and text sliding to the left. Here& ...

Dynamic Data Visualization using ChartJS with MySQL and PHP

I'm trying to create a line chart using chartJs that will display MySQL data. Specifically, I would like to use PHP to push the MySQL data to the chartJs. Here is an example of the MySQL table: id | page_views | visitors | month | ---------------- ...

Tips on how to properly format a date retrieved from a database using the JavaScript function new Date()

I've been grappling with the best method for inserting dates into the database, and currently I'm utilizing new Date(). However, when I query from the database, it returns a date format like this: 2021-09-24T12:38:54.656Z It struck me that this ...