如果这已经被问到并且我错过了,请原谅我,但这一直困扰着我整个周末,我不知道我做错了什么。我正在尝试使用 angular.js 中的 $resource 服务和 ngResource 模块发出 PUT 请求。我对 Angular 还很陌生,所以如果我再次犯新手错误,我很抱歉……在学习曲线上。
我遵循了官方页面底部的 Angular 文档指南:
https://docs.angularjs.org/api/ngResource/service/ $resource
我正在向我的后端发出 GET 请求并拉入一个“组”对象,其中一个属性称为“团队”,它是一个空数组。
然后,我可以让用户通过表单创建团队,然后将其保存到 mongodb。我自动希望将团队添加到他们所属的用户组中,因此我希望组对象将团队添加到团队数组中,然后执行 PUT。我有一个 Groups 服务,我将其作为控制器的依赖项注入。我正在执行以下操作:
app.controller('teamsController', ['$scope', '$http', '$routeParams', '$location', 'Teams', 'Groups', function ($scope, $http, $routeParams, $location, Teams, Groups) {
$scope.createTeam = function () {
var team = new Teams({.... }); //create the new team with all the data required
var groupId = this.team.group; //get the id to pull the correct group id from mongodb
//use Groups service to pull in the group to update, save it as a variable group
Groups.get({groupId: groupId}).$promise.then(function(group) {
var group = group;
group.teams.push(team); //push the team to the teams array in the group
console.log(group); //This logs exactly what I am hoping for with the new team in the teams array on the group object
//save the new team to the database, update the group by adding the new team to the teams array then go to the new team page
team.$save(function (response) {
Groups.update({id: groupId}, group);
$location.path("teams/" + response._id);
});
});
};
}]);
我的团队按照应有的方式创建,并且我在 PUT 请求上从服务器成功返回 200,但由于某种原因,团队没有被添加到组对象上的团队数组中。如果我遗漏了一些公然的东西......提前道歉。任何帮助将不胜感激。这是我的群组服务:
app.factory('Groups', ['$resource', function('$resource') {
return $resource(
'api/v1/groups/:groupId',
{
groupId: '@_id'
},
{
update: {method: 'PUT'}
}
);