Creating an object in AngularJS by merging data from three separate API calls

I am looking to develop a Jenkins dashboard using AngularJS. I am considering combining data from three different API calls to create an object that can be used in the HTML file with ng-repeat, but I'm not sure if this is the best approach.

The desired data structure is as follows:

JSON object

{
  "Job1": {
    "branchname1": {
      "stagename1": {
        "stage_status": "SUCCESS"
      },
      "stagename2": {
        "stage_status": "FAILED"
      }
    }
  },
  "Job2": {
    "branchname1": {
      "stagename1": {
        "stage_status": "SUCCESS"
      },
      "stagename2": {
        "stage_status": "FAILED"
      }
    }
  }
}

AngularJS code

angular.module('App')
  .controller('IndexCtrl', function($scope, $route, $routeParams, $rootScope, $http, $location, $log, $q, moment, $filter) {

    $scope.api = 'http://127.0.0.1:8080';
    $scope.customer = '';
    $scope.jobs = [];

    function getJobs(customer, callback) {
      $scope.customer = customer;
      $http.get($scope.api + '/job/' + customer + '/api/json?tree=jobs[name]').then(function(response) {
        angular.forEach(response.data.jobs, function(value, index) {
          $scope.jobs.push(value.name);
        });
        callback(response);
      },
      function(error) {
        alert("Could not fetch jobs from " + $scope.api);
      });
    }

    function getData(resp) {
      requests = [];
      angular.forEach(resp.data.jobs, function(value) {
        requests.push($http.get($scope.api + '/job/' + $scope.customer + '/job/' + value.name + '/api/json'));
         console.log(value.name); // OUTPUT: Job1 Job2
      });

      $q.all(requests).then(function(result) {
        angular.forEach(result, function(value) {
          angular.forEach(value.data.jobs, function(index) {

            if(index.name.match( /(hotfix|release|master)/ )) {

              console.log(index.name); // OUTPUT: branchname1 branchname2
              $http.get($scope.api + '/job/' + $scope.customer + '/job/' + value.data.name + '/job/' + index.name + '/wfapi/runs').then(function(response) {

                angular.forEach(response.data[0].stages, function(index) {
                  console.log(index.name); // OUTPUT: stagename1 stagename2
                  console.log(index.status); // OUTPUT: SUCCESS FAILED
                });
              });
            }
          });
        });
      });
    }
    getJobs("project1", getData);
  })

Is it feasible to create an object based on the outputs shown in console.log? If not, what would be the best approach to achieve a similar result?

Thank you in advance.

Answer №1

Utilize AngularJS $q.all method to construct objects from multiple API calls. In contrast to ES6 JavaScript Promise.all, AngularJS $q.all accepts a hash object of promises.

Begin by refactoring the getJobs function to return a promise:

function getJobs(customer) {
    var url = $scope.api + '/job/' + customer + '/api/json?tree=jobs[name]';
    var promise = $http.get(url);
    var newPromise = promise.then(function(response) {
        var jobs = [];
        angular.forEach(response.data.jobs, function(value, index) {
            jobs.push(value.name);
        });
        return jobs;
    },function(error) {
        alert("Could not fetch jobs from " + $scope.api);
        throw error;
    });
    return newPromise;
}

Then utilize that function to create a hash object for resolution with $q.all:

var dataPromise = getJobs("project1").then(function (jobs) {
    var dataPromiseObj = {};
    angular.forEach(jobs, function (job) {
        dataPromiseObj[job] =  getDataForJob(job);
    });
    return $q.all(dataPromiseObj);
});

dataPromise.then(function(dataObj) {
    console.log(dataObj);
});

The .then method generates a new promise which is resolved or rejected based on the return value of the successCallback, errorCallback (unless the value is a promise, in which case it is resolved with the value that is resolved in that promise using promise chaining).

For further details, refer to

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 variable in my scope is not reflecting the changes in the HTML view

Here is my code for handling file attachments in AngularJS: $scope.attachments = []; $scope.uploadFile = function(files){ for(var i=0; i<files.length; i++){ $scope.attachments.push(files[i]); console.log($scope.attachments.length); } } ...

Ionic - Landscape Mode Causing Alignment Distortion

I'm currently working on designing a grid-based image display for an Ionic Mobile App. One of the main challenges I'm facing is adjusting the heights of the images based on the screen size. I want to set a maximum height for both portrait and lan ...

How can JHipster components be effectively shared with other projects for optimal usage?

Exploring JHipster, the Spring Boot + AngularJS application generator based on Yeoman has been an interesting and fun experience. Setting up a vanilla webapp was relatively easy. Now, the goal is to separate entities, repositories, and services from the o ...

Utilizing Angular routes within a Node.js application deployed on Heroku

I've been working on deploying an AngularJS project to Heroku. The app functions perfectly fine locally and when using heroku local web. However, upon attempting to access it, I encounter the error TypeError: response.sendFile is not a function. Ser ...

How can I retrieve an image from a JSON response using Swift 3 and Alamofire?

Is there a way to retrieve an image from JSON using Alamofire and Swift 3? I have successfully extracted data in the form of a dictionary. Below is the JSON response that I received from the API, showcasing the data. While I am able to display textual info ...

Having trouble sending data to API with Node, Express, and vanilla JavaScript POST form

I am currently utilizing Node JS along with Express JS in order to implement a form submission that pushes data into the database. Below is my form structure <form action="/pokedex/register/poke_submission" method="POST"> ...

Gather a combination of key-value pairs from JSONArrays in Java and consolidate them into a single JSONArray

I am working on a task involving JSONObject, with two JSONArray to extract key and value pairs and return them as a new JSONArray: The first JSONArray contains two objects shown below: [{"name": "John", "id": "1"}, ...

Charting data with missing values in Google Charts

I have generated a line chart using php and json to load the data. The issue I am facing is that the chart displays NULL values as 0, which does not look good. My assumption is that I may be formatting the json incorrectly, and what I really need is {"v" ...

Tips on preventing the use of backslashes in JSON output from PHP

I'm encountering an issue with the code provided below. The console log is showing: "returningList{"view":0,"new":1,"random":1} result: "{\"view\":0,\"new\":1,\"random\":1}"" It seems that the JSON data is getting back ...

The process of initializing the Angular "Hello World" app

Beginning with a simple "hello world" Angular app was going smoothly until I attempted to add the controller. Unfortunately, at that point, the expression stopped working on the page. <!doctype html> <html ng-app='app'> <head> ...

Guide to using a JSON WCF service in C#

I have a JSON web service. The address is provided. The WSDL code includes the following: <wsdl:binding name="BasicHttpBinding_iBOER" type="tns:iBOER"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" /> - <wsdl:operation n ...

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

Persistent hover state remains on buttons following a click event

In my current project, I am dealing with a form that has two distinct states: editing and visible. When the user clicks on an icon to edit the form, two buttons appear at the bottom - one for saving changes and one for canceling. Upon clicking either of th ...

Error handling JSON in Spring

After attempting the following code: @RequestMapping(method = RequestMethod.GET, value = "/getmainsubjects") @ResponseBody public JSONArray getMainSubjects( @RequestParam("id") int id) { List <Mainsubjects> mains = database.getMainSubjects(id, Loca ...

Problem with retrieving information from an array of objects - Vue.js / accessing API / utilizing axios / implementing proxy

Currently, my project involves using Vue.js to connect to an API and retrieve data using axios with a proxy. I am facing difficulty accessing the property of an object nested within multiple arrays. Below are more details: View Global details Property I& ...

Generating a JSON file within Codepen for use in AngularJS

I am trying to populate a web table using an external JSON file, but it is blocked by CORS policy. Is there a way I can declare the object locally instead? Check out the Codepen for more details: https://codepen.io/centem/pen/Rwbmmdy Thank you. var app ...

Confirm the checkboxes that are necessary

In the realm of my AngularJS project, I am eager to develop a terms and conditions form. Among multiple checkboxes, only select few are deemed necessary. My aim is to activate the submit button solely when all required checkboxes have been checked. Below ...

Utilize the dynamic duo of GridLayout and ScrollView within the Famo.us JS framework

I'm attempting to incorporate a grid layout into a scroll view using famo.us (with angular), and the most straightforward approach seems to be working. <fa-view> <fa-scroll-view fa-pipe-from="eventHandler" fa-options="scrollView"> ...

resolved promise's then method was not invoked

Attempting to stub a method using sinon, jasmine, and $q. Wanting the method to return fake data. An issue arises where the defined then statement is never executed, and the reason remains unknown. The stub is invoked The console log displays Steven Stu ...

Tips on personalizing the BROWSERSTACK_BUILD_NAME within Jenkins

Currently, I am in the process of incorporating BrowserStack into my Selenium Python framework and utilizing Jenkins for running tests. However, I am encountering difficulties when trying to personalize the build name on the BrowserStack dashboard. ...