【问题标题】:Posts are not refreshing when removing one from the database从数据库中删除帖子时不刷新帖子
【发布时间】:2017-12-30 09:49:49
【问题描述】:

我正在使用 MEAN 堆栈制作一个简单的博客,但遇到了一个简单的问题。

这是我用来检索所有帖子的 HTML 部分:

index.html:

<div ng-repeat="post in posts">
  <h2>
    {{post.title}}
    <a ng-click="deletePost(post._id)"class="pull-right"><i class="fa fa-times" aria-hidden="true"></i></a>
  </h2>
  <em>{{post.posted}}</em>
  <p>{{post.body}}</p>
</div>

请注意:&lt;i class="fa fa-times" aria-hidden="true"&gt;&lt;/i&gt; 是取自 FontAwesome 库的图标

这是我的 Angular 应用控制器:

(function () {
  angular
    .module("BlogApp", [])
    .controller("BlogController", BlogController);

    function BlogController($scope, $http) {
      $scope.createPost = createPost;
      $scope.deletePost = deletePost;

      function init() {
        getAllPosts();
      }
      init();

      function deletePost(postId) {
        $http.delete('/api/blogpost/' + postId).then(getAllPosts);
      }
      function getAllPosts() {
        $http.get("/api/blogpost").then(function(posts){
        $scope.posts = posts.data
    });
  }

这是我的服务器处理删除请求的部分:

// deletePost
app.delete('/api/blogpost/:id', deletePost);

function deletePost(req, res) {
  var postId = req.params.id;
  PostModel.remove({_id: postId}).then(
    function() {
      res.sendstatus(200);
    },
    function() {
      res.sendStatus(400);
    }
  );
}

单击 X 图标时,该操作确实会命中我的控制器,到达服务器并设法从我的数据库中删除帖子,但由于某种原因,它不会使用我的所有帖子自动更新页面。我必须刷新它。这就是为什么我认为在访问服务器后立即在控制器中调用函数getAllPosts 会更新数据。我错过了什么?

【问题讨论】:

  • 不应该是$scope.post吗?
  • 好吧,我将标题和正文的模型添加为ng-model="post.title",因此帖子是帖子对象的数组。老实说,我不知道写错了什么,但是我在服务器中重新编写了deletePost 函数,现在它可以工作了。我认为这是猫鼬承诺的问题。老实说,我仍然觉得这很令人困惑。
  • 那你应该回答你的问题接受并关闭它

标签: angularjs node.js mongodb mean-stack


【解决方案1】:

在删除特定帖子后,我最终重新编写了 mongoose 承诺并且它起作用了。

// deletePost
function deletePost(req, res) {
  var postId = req.params.id;
  PostModel.remove({ _id: postId}).then(function(err){
    if (err) { console.log(err); }
    res.send('Post deleted');
  });
}

这似乎也有效:

function deletePost(req, res) {
  var postId = req.params.id;
  PostModel.remove({ _id: postId}).then(
    function(status) {
      res.sendStatus(200)
    }, function() {
      res.send(400);
    }
  );
}

对于如何使用 mongoose 承诺仍然有点困惑......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    相关资源
    最近更新 更多