Javascript AngularJS$resource-更新对象内的数组

Javascript AngularJS$resource-更新对象内的数组,javascript,arrays,angularjs,mongodb,api,Javascript,Arrays,Angularjs,Mongodb,Api,我试图弄清楚如何使用API更新javascript对象中的数组。例如,我可以提取/api/posts/:id的完整端点,并得到以下结果: {"_id":"56521356177af21100960105", "user":"564bbd2da851f0aaeb7746c5", "description":"'Taking You Higher' Pt. 3 Support here... http://bit.ly/YJBeIg So a year after 'Taking You H

我试图弄清楚如何使用API更新javascript对象中的数组。例如,我可以提取/api/posts/:id的完整端点,并得到以下结果:

    {"_id":"56521356177af21100960105",
"user":"564bbd2da851f0aaeb7746c5",
"description":"'Taking You Higher' Pt. 3 Support here... http://bit.ly/YJBeIg So a year after 'Taking You Higher' Rameses B and I decided to put out another summery progres...",
"title":"'Taking You Higher Pt. 2' (Progressive House Mix) - YouTube","comment":"This is a great mix.","url":"https://www.youtube.com/watch?v=heJBwBUStXU","__v":0,
"created":"2015-11-22T19:11:18.760Z",
"group":["564fddfbf5d334fc0f6b4093"]}
我想关注对象中的“组”数组。我正在寻找一种通过使用AngularJs添加和删除项目来更新数组的方法。据我所知,我很可能需要使用$resource而不是$http。然而,我不知道这应该怎么写

以下是迄今为止我在控制器中的内容:

myApp.factory('groupsInPost', function($resource) {
  return $resource('/api/posts/:id', { id: '@_id' }, {
    update: {
      method: 'PUT' // this method issues a PUT request
    }
  });
});

正如您可能马上就会想到的,我当前的问题是,我的API没有像$resource所期望的那样发回数组。我不知道从这里到哪里去。如果你有任何见解,这将是非常有帮助的


谢谢,

我有点不明白为什么要调用
$scope.groups.data
data
是否是API对
GET
请求的响应的一部分

此外,根据发布的代码,您在更新呼叫期间检索组列表。既然
$resource
帖子相关,那么之前不应该这样做吗?在你加载帖子的时候,它看起来更合理

在注释行中,您将
组id
推送到组列表。它来自哪里

假设你想保持这种流动,我的建议如下:

var group_id = 1;
$scope.post = groupsInPost.get({ id: post_id }, function() {
  $scope.post.group.push(group_id);

  $scope.post.$update(function() {
    // updated in the backend
  });
});

如果我在问题上遗漏了什么,请告诉我,这样我就可以相应地更新我的答案了

此代码工作得非常好。非常感谢你。关于你的问题,控制器中的额外代码只是我以前尝试过的额外代码。我只是把这些放在这里,作为先前尝试的参考。我有一次跟进。您提供的代码向我展示了如何根据请求将内容推送到阵列。我也在寻找从数组中删除某些项目的方法。那么,假设您将group\u id添加到数组中,那么删除group\u id的代码会是什么样子?提前感谢您?您需要首先找到它的索引:
var i=$scope.post.group.indexOf(group\u id)然后删除它:
如果(i!=-1){$scope.post.group.splice(i,1);}
var group_id = 1;
$scope.post = groupsInPost.get({ id: post_id }, function() {
  $scope.post.group.push(group_id);

  $scope.post.$update(function() {
    // updated in the backend
  });
});