AngularJS在PUT请求后重新加载数据

时间:2014-07-15 16:16:52

标签: angularjs mongodb express request put

对于知道Angular的人来说,这应该是一个相当容易的人。我正在尝试更新在我发出PUT请求以更新对象后显示的数据。这是一些代码:

邮政服务(services / post.js)

'use strict';

angular.module('hackaboxApp')
  .factory('Post', function($resource) {
    return $resource('/api/posts/:id', {id : '@id'}, {
        'update': { method: 'PUT' }
    })
});

尝试更新数据时执行的服务器端控制器功能(lib / controllers / api.js)

exports.editsave = function(req, res, next) {
  var posty = req.body;

  console.log(posty._id.toString() + " this is posty");

  function callback (err, numAffected) {
    console.log(err + " " + numAffected);
    if(!err) {
      res.send(200);
      //res.redirect('/forum');
    }
  }

  Post.update(posty, { id: posty._id.toString() }, callback);
};

这是上述代码的控制台输出:

53c54a0d4960ddc11495d7d7 this is posty
null 0

正如您所看到的,它不会影响任何MongoDB文档,但它也不会产生错误。

当帖子更新时,客户端(Angular)端会发生这种情况:

$scope.saveedit = function() {
      console.log($scope.post._id + " post id");
      // Now call update passing in the ID first then the object you are updating
      Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};

重定向后,$location.path('/forum'),没有任何数据显示为更新...当我查看数据库时...没有任何改变...就像我错过了save更改...但我认为updatePUT请求)会为我做这件事。

我在加载ng-init="loadposts()"路由时使用/forum

$scope.loadposts = function() {
      $http.get('/api/posts').success(function (data) {$scope.posts = data});
};

此后不应该加载所有新数据吗?任何帮助,将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

好的,我明白了。

问题是你没有使用Angular资源api正确。

此代码需要更改:

$scope.saveedit = function() {
   console.log($scope.post._id + " post id");
   Post.update({ id:$scope.post._id }, $scope.post, function()     {$location.path('/forum')});
};

分为:

    // Update existing Post
    $scope.saveedit = function() {
        var editedpost = new Post($scope.post); //New post object

        editedpost.$update(function() {
            $location.path('/forum');
        }, function(errorResponse) {
            $scope.error = errorResponse.data.message;
        });
    };

至于服务器代码(取自我自己的工作模块):

exports.update = function (req, res) {
    var post == req.post;

    post = _.extend(post, req.body);

    post.save(function (err) {
        if (err) {
            return res.send(400, {
            message: getErrorMessage(err)
        });
    } else {
        res.jsonp(post);
    }
});

};

答案 1 :(得分:0)

您的服务器端输出表明更新查询与数据库中的任何文档都不匹配。

我猜你在NodeJS服务器端代码中使用Mongoose连接到mongodb。

如果是这种情况,您的更新声明似乎不正确。

  1. 而不是{ id: .. }应该是{ _id: .. }
  2. 还交换了条件对象和更新的对象。
  3. 声明应该是这样的:

    Post.update({ _id: posty._id.toString() }, posty, callback);
    

    如果您没有使用Mongoose,请详细说明您使用的库或更好的库,请显示在服务器端代码中定义Post变量的代码。

相关问题