Querying data from a promise and embedding it in a JSON object in AngularJS

Attempting to retrieve data from a promise within a JSON object for the first time has presented me with a challenging task.

The typical approach looks something like this:

Service JS

 app.factory("dataService", ["$http",
    function ($http) {
      function getData(id) {
        return $http.get('endpoint', id)
            .then(function (response) {
                return response.data
            });
    }

   return {
     getData: getData
   }

}])

Controller JS

$scope.data = {}

dataService.getData($routeParams.id)
   .then (function (res) {
        $scope.data = res
    });

This method works well and satisfies everyone involved.

Now, I am attempting to assign data within an object.

Controller JS

 angular.forEach($scope.properties, function (item) {
                      $scope.data.properties.push({
                          order: item.number,
                          name: item.name,
                          value: item.value,
                          items: $scope.getProp(item.id)
                      })
                  });

 $scope.getProp = function (id) {
            return dataService.single(id)
                .then (function (res) {return res});
        };

Service JS

function single(id) {
            return $http.get('endpoint' + "/" + id)
                .then(function (response) {
                    return response.data
                })
        }

Now, I am encountering a JSON object with a promise and $$state inside.

I comprehend the complexity of this issue, but solving it exceeds my current knowledge. Can anybody offer assistance in resolving this challenge?

Answer №1

To ensure everything runs smoothly, one method to consider is:

$scope.data.properties = [];
var promiseList = $scope.properties.map(function(item) {

    var promise = $scope.getProp(item.id);

    return promise.then(function (data) {
        var newItem = {
            id: item.id,
            order: item.number,
            name: item.name,
            value: item.value,
            items: data
        };   
        $scope.data.properties.push(newItem);
        return newItem;
    });
});

$q.all(promiseList).then(function(itemList) {
    console.log(itemList);
    //Additional code can be added here
});

In the example above, an array of promises is generated. Each promise resolves to objects with the items property filled with data from the promise linked to $scope.getProps.

Furthermore, each complete item is added to scope. Due to asynchronous XHRs possibly finishing out of sequence, the scope list may not match the original order.

Nonetheless, the $q.all method stands by to patiently wait for all XHRs to finish and deliver the list in its initial order.

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

Tips for Resizing and Reviving Divs with jQuery

I have recently ventured into the world of web development to assist a family member with their website. My knowledge and experience are limited, but I am facing an interesting challenge. I am trying to manipulate certain divs as users scroll down the page ...

Utilizing classes as types in TypeScript

Why is it possible to use a class as a type in TypeScript, like word: Word in the provided code snippet? class Dict { private words: Words = {}; // I am curious about this specific line add(word: Word) { if (!this.words[word.term]) { this.wor ...

Clicking on a button within the parent element will enable you to remove the parent element multiple times with the use of VanillaJS

Within a ul element, each li contains multiple elements in the following structure: <ul> <li> <div> <p>some text </p> <button>delete</button> <div> </li> <li> ...

Ways to determine the overall cost of a shopping cart using Vuejs Vuex

Running a business requires managing various aspects, including tracking the inventory. In my store, I have an array called basketContents that contains items with their respective quantities and prices. An example of how it looks is: state: { basketConte ...

Problems arise when JQuery fails to function properly alongside ajax page loading

While utilizing ajax to load the page, I encountered an issue where the jQuery on the loaded page template was not functioning until the page was manually refreshed. The ready function being used is: jQuery(document).ready(function() { jQuery(' ...

Add a plethora of images to the canvas

Just starting out with Fabric.js and trying to figure out how to draw a picture on the canvas after a drop event. I managed to do it once, but am struggling with inserting more pictures onto the canvas (each new drop event replaces the previous picture). ...

Looking for a pattern that combines Browserify and Angular?

Currently, I am embarking on a project using angular and browserify for the first time. I am seeking advice on how to properly utilize the require function with browserify. There are multiple ways to import files, but so far, I have experimented with the ...

What is the best way to vertically flip a background image that is repeating along the y axis in CSS?

I am in the process of developing a mobile web app and I need assistance with flipping the background image when it repeats along the y-axis. Can someone guide me on how to achieve this using CSS or JavaScript? https://i.stack.imgur.com/b107V.jpg var el ...

Add some TD(s) after the td element

The HTML code I currently have is as follows: <tr> <td class="success" rowspan="1">Viability</td> <td data-rowh="-Checksum">Viability-Checksum</td> </tr> <tr> ...

I am currently utilizing AngularJS alongside Django-cors-headers, which results in the restriction of certain actions for cross-origin requests that necessitate preflight

My Django local server is running on port 8000, and I have a local Nginx server loading an HTML page on port 2080. To resolve cross-domain errors, I have installed the django-cross-header package. In my settings.py, I have configured django-cross-header ...

Tips for Including a Parallax Image Within a Parallax Section

Currently, I am working on implementing a parallax effect that involves having one image nested inside another, both of which will move at different speeds. My progress has been somewhat successful, however, the effect seems to only work on screens narrowe ...

UI-Router - Displaying and concealing elements dynamically in response to state changes

I am currently dealing with a situation where I have implemented dynamic showing and hiding of a button based on state changes. However, there seems to be a noticeable delay when the button is supposed to hide. The button itself is created as a directive ...

How come I am unable to pass JavaScript values to my PHP5 code?

I'm struggling with this code snippet: <?php $html=file_get_contents('testmaker_html.html'); echo $html; ?> <script type="text/javascript"> document.getElementById('save_finaly_TEST').addEventLis ...

Encountering the error message "Unable to access /" on the browser when using express router

Just started working with the express Router for the first time. Here is my route.js: var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('home page'); }); module.e ...

Tips for eliminating flutter for static menu with easyResponsiveTabs.js

Experiencing a flickering issue with the fixed menubar and easyResponsiveTabs.js in my project when scrolling down. Attempted to resolve it using jquery.noConflict(), but without success. Would appreciate any guidance on how to address this problem. ...

Retrieving a JavaScript variable from a different script file

I have a JavaScript script (a) with a function as follows: function csf_viewport_bounds() { var bounds = map.getBounds(); var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); var maxLat = ne.lat(); var maxLong = ne.lng(); ...

Troubleshooting: React js Project console.logs are not being displayed in the browser's

When working on my current project, I noticed that any time I try to use console.log in the dev tools, it shows as cleared. Strangely, console.log works fine in my other projects. Does anyone have an idea how to resolve this issue? Here is a screenshot of ...

The ng-class directive is failing to work properly when receiving a parameter from an HTTP response

I'm working on utilizing a servlet that delivers a JSON object with a parameter called "valoracion." My goal is to assign this parameter as a CSS class for a span label based on the value associated with it. By doing so, I aim to display a .gif in a u ...

Express is unable to locate the specified property

Here is my controller code snippet: exports.showit = function(req, res){ res.render('showpost', { title: req.post.title, post: req.post }) } In my post model, I have included title and name objects: title: {type : String, default : &apos ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...