我有一个通过“app.factory”附加到 angular app 模块的功能,其中包含某些 http 请求。该函数在控制器中被调用,并且从函数返回的数据被分配给控制器中的作用域变量。
问题是首先执行控制器,然后执行函数中的 http 请求,因此无法将来自 http 请求的数据捕获到范围变量中。如何纠正。
function resourceapp.factory('dataService', function($http){
var data = {};
data.EnterprisePrograms = [];
data.Resources=[];
data.Skills=[];
data.Allocations=[];
Execution = function($http) {
$http.get('http://localhost:8080/api/enterpriseProgram')
.then(function(resources) {
data.EnterprisePrograms=resources.data;
});
$http.get('http://localhost:8080/api/resource')
.then(function(resources) {
data.Resources=resources.data;
});
$http.get('http://localhost:8080/api/skill')
.then(function(resources) {
data.Skills=resources.data;
});
$http.get('http://localhost:8080/api/allocation')
.then(function(allocation) {
data.Allocations = allocation.data;
});
}
return data;
});
控制器
resourceapp.controller('AllocationList', function($scope, dataService) {
$scope.allocationList = dataService.Allocations;
});
它应该是这样的:
在工厂中:创建一个方法来返回承诺。
resourceapp.factory('dataService', function($http){
var data = {};
data.getEnterprisePrograms = function($http){
return $http.get('http://localhost:8080/api/enterpriseProgram');
}
data.getResourceData = function($http) {
return $http.get('http://localhost:8080/api/resource');
}
data.getSkillData = function($http) {
return $http.get('http://localhost:8080/api/skill');
}
data.getAllocationData = function($http) {
return $http.get('http://localhost:8080/api/allocation');
}
return data;
});
在 Controller 中,调用工厂方法来获取承诺并使用$q.all()
resourceapp.controller('AllocationList', function($scope, dataService, $q){
var allocationPromise = dataService.getAllocationData();
var skillPromise= dataService.getSkillData();
// other promise
$q.all([allocationPromise,skillPromise, ..other promise]).then(function (result) {
$scope.allocationData = result[0].data;
$scope.skillData = result[1].data;
// other data
})
});
见这对$q.all()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句