[英]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.