Search code examples
javascriptangularjsangular-resource

cannot read property '$remove' of undefined ngResource


I have a working api in my server, my CRUD module work just fine and I can get, post, put, delete in my server

I also have CRUD module in my angular controller, which all works fine except the delete function

I am using ngResource $save, $update, and $remove for manipulating data in client all the way to the server

the $save and $update works just fine, but $remove returns me an error: "cannot read property $remove of undefined"

here is my controller

$scope.findOne = function () {
    $scope.post = Posts.get({
        postId: $routeParams.postId
    });
};

$scope.update = function () {
    $scope.post.$update(function () {
        $location.path('posts/' + $scope.post._id);
    }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
    });
};

$scope.delete = function (post) {
    if (post) {
        post.$remove(function () {
            for (var i in $scope.posts) {
                if ($scope.posts[i] === post) {
                    $scope.posts.splice(i, 1);
                }
            }
        });
    }
    else {
        $scope.posts.$remove(function () {
            $location.path('posts');
        });
    }
};

my service

angular.module('posts').factory('Posts', ['$resource',
    function ($resource) {
        return $resource('posts/:postId', {
            postId: '@_id' 
        }, {
            update: {
                method: 'PUT'
            }
        });
    }
]);

the weird thing is, the update, works, but the delete doesn't work

Is it because of the argument I have in the delete method?

here is my view

<div data-ng-controller="PostsCtrl">
<section data-ng-init="findOne()">
    <div data-ng-show="authentication.user._id === post.author._id">
        <a href="/#!/posts/{{post._id}}/edit">Edit</a>
        <a href="#" data-ng-click="delete()">delete</a>
    </div>
</section>
</div>

Why I can't delete the post and it returns undefined? Is $remove no longer used in ngResource?

what are the methods available in ngResource?


Solution

  • Use Posts.remove or $scope.post.$remove like

    $scope.post.$remove(successCallBack,errorCallBack) //careful the item ($scope.post) will be removed.
    

    or

    Posts.remove({},{postId: 'your post id'})
    

    The parameter of $scope.delete method doesn't contain the reference of $resource