Home Posts are not refreshing when removing one from the database
Reply: 1

Posts are not refreshing when removing one from the database

user7496931
1#
user7496931 Published in 2017-12-07 19:18:48Z

I'm making a simple blog using a MEAN stack, and i'm running into a simple issue.

Here's the html portion i'm using to retrieve all my posts:

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>

Note that: <i class="fa fa-times" aria-hidden="true"></i> is an icon taken from the FontAwesome library

Here's my controller for the angular app:

(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
    });
  }

And here's the portion of my server handling the delete request:

// 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);
    }
  );
}

When clicking on X icon, the action does hit my controller, reaches the server and manages to delete the post from my database but for some reason, it doesn't update the page automatically with all my posts. I have to refresh it. That's why I thought invoking the function getAllPosts in the controller right after hitting the server would update the data. What am I missing?

user7496931
2#
user7496931 Reply to 2017-12-07 19:38:09Z

I ended up re-writing the mongoose promise after removing the specific post and it worked.

// 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');
  });
}

This also seems to work:

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

Still a bit confused as to how to work with the mongoose promises...

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.344349 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO