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

How can you make a button in Vue only visible after all API calls have successfully retrieved the data?

Is there a way to make the report button visible only after all the data has been loaded from the latest click of the budget button? Currently, when the budget button is clicked, it retrieves budgets and displays them in a Vue grid using Kendo Grid. To spe ...

Integrating additional JavaScript into an Ionic 2 project

Imagine we have a foo.js file containing a variable, function, and class that are not yet part of the project. Now suppose we want to access these elements in our home.ts method or make them globally available for use within a home.ts method. How can this ...

Angular.js has encountered an error due to exceeding the maximum call stack size

Hello everyone! I attempted to create recursion in order to extend my $routeProvider in Angular.js with the following code: var pages = { 'home': { 'url': '/', 'partialName': 'index', ...

Tips for preventing the use of website URLs as variables in jQuery ajax() calls:

Having some trouble. For example: $(document).ready(function () { $("#btnSend").click(function () { var noti_p = { url: "Pusher_Controller.ashx", data: "&appname=" + $("#selt1").val() + "&title=" + $("#title"). ...

A guide to setting an href using variable values in jQuery through manual methods

I have a datepicker set up where each day, month, and year is stored in a variable. I then display this information in the desired format. Below is the jQuery code: jQuery(document).ready( function($){ alert('alert function'); var txtFr ...

AngularJS select ng-model not correctly updating values

My form features a simple select element containing all the states along with their abbreviations. When I use the keyboard to navigate, I encounter an issue where the ng-model value does not change properly on the second keypress under certain circumstance ...

What is the best way to preserve an apostrophe within a variable in JavaScript without it being replaced?

How can I send the value of NewText in its original form from .cs code using an ajax call? **var NewText ="D'souza";** $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: " ...

How can we use the useState hook in React to dynamically generate state variables?

I'm currently working on a React app where input fields need to be stored in the state. While I can use the useState hook to easily store these values, the challenge I'm facing is that I don't know what fields are needed since they are retri ...

Modify parameters variable when searching by utilizing bootgrid along with structured-filter

I have implemented both https://github.com/evoluteur/structured-filter and to develop an advanced search functionality using ajax/php. Initially, the code is functioning correctly and retrieves data from the php file. However, I am facing difficulties wh ...

An issue occurred with the DOMException while trying to execute the 'setAttribute' function on the 'Element': '{{' is an invalid attribute identifier

Currently, the code is under development and some methods are still empty while the *ngIf directives may not be correct in terms of logic. However, even with these issues, I encountered the same error without bothering to remove them at this stage. While ...

A stylish method for converting CSV data into XML format using Node.js and Express

I am in search of a sophisticated solution to convert CSV files into hierarchical XML format based on a specific template within a Node/Express server. For example, if the CSV is of Type Template "Location": Name,Lat,Lon,Timezone name,lat,lon,timezone it ...

To set up MongoDB on your system, execute the following command: `npm install --

I've encountered a problem while attempting to install MongoDB on my personal computer for a Node project. I used the command line and ran npm install --save mongodb. Even though MongoDB appears in the dependencies section of my package.json file with ...

The error encountered in the Node crud app states that the function console.log is not recognized as a

I am attempting to develop a CRUD application, however, I keep encountering an error message that states "TypeError: console.log is not a function" at Query. (C:\Users\Luis Hernandez\Desktop\gaming-crud\server\app.js:30:25) h ...

Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError bl ...

Can the getState() method be utilized within a reducer function?

I have encountered an issue with my reducers. The login reducer is functioning properly, but when I added a logout reducer, it stopped working. export const rootReducer = combineReducers({ login: loginReducer, logout: logoutReducer }); export c ...

Reactjs implemented with Material UI and redux form framework, featuring a password toggle functionality without relying on hooks

Currently, I am working on a react project where I have developed a form framework that wraps Material-UI around Redux Form. If you want to check out the sandbox for this project, you can find it here: https://codesandbox.io/s/romantic-pasteur-nmw92 For ...

Vue 3 - Compelled to utilize any data type with computedRef

Recently, I've been diving into Vue/Typescript and encountered a puzzling error. The issue revolves around a class named UploadableFile: export class UploadableFile { file: File; dimensions: Ref; price: ComputedRef<number>; ... constr ...

Creating a dynamic category menu using angularJS

I'm struggling with the logic behind creating a category menu using AngularJS I need to display all categories with a parent category id of 0. Once that is done, I want to display all subcategories that belong to each parent category. The final categ ...

Troubleshooting: Issues with accessing object properties in a function in AngularJS

In my controller, I have a function that checks the day and changes the isOpen property of an object based on the time. The object is retrieved using the code snippet below: $http.get('js/data.json').success(function(data) { $scope.locations = ...

Angular decode UTF8 characters with pascalprecht.translate

I'm facing issues with UTF8 characters when using SanitizeValueStrategy('sanitize'). This is necessary because the client will be editing texts in language files and may include tags like <b> or <i>... I want to rely exclusively ...