因此,我正在对AngularJS进行实验,并且,作为练习,我想我将使用蒸汽API创建一个简单的应用程序。我做了一个简单的Spring服务,它为蒸汽API提供了反向代理服务,这样就可以转发某些调用。目前有两个行动:
/user/提供了一个蒸汽id列表。/user/:id/games提供了以下api的输出:ID&format=json
它以下列格式返回答案:
{
"response":{
"game_count":3,
"games":[
{
"appid":70000,
"playtime_forever":0
},
{
"appid":550,
"playtime_forever":0
},
{
"appid":274900,
"playtime_forever":0
}
]
}
}我想要实现的是从这个json对象中提取games数组,并将它附加到正确的用户。我想为所有用户做这件事。通过定义以下工厂,我已经使用$resource对象实现了与我想要的接近的目标:
angular.module("SAM.Resources", [])
.factory("UserList", ["$resource",
function ($resource) {
return $resource('/user');
}])
.factory("GamesList", ["$resource",
function ($resource) {
return $resource('/user/:id/games', {
id: '@id'
});
}
]);然后在我的控制器中使用以下内容:
UserList.query(function(response){
$scope.users = response ? response : [];
for(index=0; index < $scope.users.length; ++index){
user = $scope.users[index];
$scope.users[index].games = GamesList.get({id:user.id});
}
});这接近我想要的,但是,它返回某种格式的东西:
{
"id": "76561198119953061",
"name": "Yuri",
"games": {
"response": {
"game_count": 3,
"games": [
{
"appid": 70000,
"playtime_forever": 0
},
{
"appid": 550,
"playtime_forever": 0
},
{
"appid": 274900,
"playtime_forever": 0
}
]
}
}
}我不想要games.response.games的建筑。我试图将其改为:
$scope.users[index].games = GamesList.get({id:user.id}).response.games;它失败了,看起来很符合逻辑,因为它是一个承诺,并且不会立即包含响应对象。
我也试着用这样的方法
GamesList.get({id:user.id}), function(response){
angular.extend(user, response);
});它确实会将响应附加到user对象,只有user对象在承诺解析时始终是数组中的最后一个值。
因此,基本上,我的问题归结为:如何用User Games 列表扩展对象?
发布于 2015-11-17 08:19:30
您需要在以下几个方面更改代码:
UserList.query(function(response){
$scope.users = response ? response : [];
for(index=0; index < $scope.users.length; ++index){
user = $scope.users[index];
(function(index, id){
GamesList.get({id: id}, function(response){ // Get the games from the response
$scope.users[index].games = response.response.games;
}));
})(index, user.id)
}
});在for循环中,user不断地更改值。当第一个GameList.get返回一个值时,您的循环将位于最后一个用户处。
在IIFE中将这些变量包装在单独的作用域中。
发布于 2015-11-17 08:15:58
for(index=0; index < $scope.users.length; ++index){
user = $scope.users[index];
$scope.users[index].games = GamesList.get({id:user.id}, function(response){
angular.extend(user, response);
}));
}当您这样做时,用户变量在每一步都会发生变化。但匿名回调将在稍后执行。因此,只使用最后一个用户。
您可以通过使用匿名函数作为forEach的作用域来解决这个问题:
$scope.users.forEach(function(user) {
$scope.users[index].games = GamesList.get({id:user.id}, function(response){
angular.extend(user, response);
}));
});如果要避免user.games.response.games,则需要以不同的方式合并这些对象。
$scope.users.forEach(function(user) {
$scope.users[index].games = GamesList.get({id:user.id}, function(response){
user.games = response.games;
user.games_count = response.games_count;
}));
});https://stackoverflow.com/questions/33751766
复制相似问题