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

Posts are not refreshing when removing one from the database

user2050
1#
user2050 Published in April 22, 2018, 12:43 am

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?

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO