[英]How to read the data from json file and return as string or object in angularJS?
[英]How to return data from promise inside JSON object? angularjs
這是我第一次嘗試從JSON對象中的promise返回數據時,我堅持執行此任務
所以普通的方式是這樣的
服務js
app.factory("dataService", ["$http",
function ($http) {
function getData(id) {
return $http.get('endpoint', id)
.then(function (response) {
return response.data
});
}
return {
getData: getData
}
}])
控制器js
$scope.data = {}
dataService.getData($routeParams.id)
.then (function (res) {
$scope.data = res
});
這很好,每個人都很高興
現在我正在嘗試在對象內部分配數據
控制器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});
};
服務js
function single(id) {
return $http.get('endpoint' + "/" + id)
.then(function (response) {
return response.data
})
}
現在我得到帶有promise和$$ state的JSON對象
我了解此問題的性質,但是解決該問題的方法超出了我的知識范圍,因此有人可以幫助我解決該問題嗎?
使它起作用的一種方法是:
$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
});
上面的示例創建一個promise列表,這些promise返回對象,這些對象具有由$scope.getProps
返回的promise數據填充的items
屬性。
另外,它將每個填充項推到作用域。 由於異步XHR可能無法按照啟動的順序完成,因此作用域列表的順序可能與原始順序不同。
但是, $ q.all方法將等待所有XHR完成並以原始順序返回列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.