This is my first time when I try to return data from promise inside JSON object and I stuck with this task
So common way is 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 works fine and everybody is happy
now I'm trying to assign data inside 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
})
}
and now I'm getting JSON object with promise and $$state inside
I understand the nature of this problem but solution for this problem is out of range of my knowledges, so could somebody help me deal with it ?
One way to make it work 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);
//More code here
});
The above example creates a list of promises that return objects that have the items
property populated with data from the promise returned from $scope.getProps
.
In addition it pushes each populated item to scope. Because the asynchronous XHRs may not complete in the order that they were started, the scope list may not be in the same order as the original.
The $q.all method however will wait for all the XHRs to complete and return the list in the original order.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.