正如您所看到的,这是我第一次尝试这个,而且我似乎做错了。我只想采取一些代码,包括promises和http请求,并在控制器使用它之前将其放入服务中。我的目标是简单地清理控制器,使其不包含所有代码。
在控制器的最后一步中记录后,对象显示为未定义。此外,所有请求都已成功完成。所以,它正在跳过所有的箍,所以我猜它不能在服务中返回任何值,并且没有任何东西被传递给控制器中的后续函数。在承诺完成后,如何在服务中返回'people'数组?
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', function ($scope, $http, dataService) {
var getPeople = function () {
return $http.get('/getpeople');
};
getPeople().then(function (response) {
dataService.compilePeople(response)
})
.then(function (people) {
console.log(people);
$scope.people = people;
});
});
myApp.service('dataService', function ($q, $http) {
this.compilePeople = function (response) {
var people = [];
names = response.data;
grandPromiseArray = [];
names.forEach(function (index) {
var name = index,
count = $q.defer(),
skills = [],
urls = '/getskillsbyname/' + name,
urlc = '/getcountbyname/' + name;
grandPromiseArray.push(
$q.all([$http.get(urls), $http.get(urlc)])
.then(function (response) {
people.push({
name: name,
skills: response[0].data,
count: response[1].data
});
})
);
});
return $q.all(grandPromiseArray).then(function () {
return people
});
}
});
答案 0 :(得分:2)
您需要从compilePeople()
返回承诺,以便将人员传递到下一个.then()
处理程序。如此接近;)
getPeople()
.then(function (response) {
//You were missing this return
return dataService.compilePeople(response)
})
.then(function (people) {
console.log(people);
$scope.people = people;
});