gpt4 book ai didi

javascript - Angular 服务问题——在包含 promise 的服务中返回一个数组

转载 作者:行者123 更新时间:2023-11-30 16:15:02 26 4
gpt4 key购买 nike

如您所见,这是我第一次尝试这样做,但我似乎做错了。我只想获取一些代码,包括 promises 和 http 请求,并在 Controller 使用它之前将其放入服务中。我的目标是简单地清理 Controller ,使其不包含所有代码。

在 Controller 的最后一步记录它之后,对象显示为未定义。此外,所有请求都已成功发出。所以,它跳过了所有的环节,所以我猜它一定不会在服务中返回任何值,也不会传递给 Controller ​​中的后续函数。 promise 完成后如何返回服务中的 '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
});
}
});

最佳答案

您需要从 compilePeople() 返回 promise ,以便将人员传递到下一个 .then() 处理程序。如此接近 ;)

getPeople()
.then(function (response) {
//You were missing this return
return dataService.compilePeople(response)
})
.then(function (people) {
console.log(people);
$scope.people = people;
});

关于javascript - Angular 服务问题——在包含 promise 的服务中返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35660937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com