Search code examples
javascriptangularjsangular-resource

Angular CRUD parsing ID on resource remove


I'm trying to write a function to remove an answer:

// Remove an answer
$scope.removeAnswer = function(answer) {
  Answers.remove(answer._id);
};

However, I am throwing the console error:

DELETE http://localhost:9000/api/answers?0=5&1=4&10=7&11=4&12=2&13=c&14=0&15=0&16=0&17=0&18=0&19=0&2=7&20=0&21=0&22=0&23=4&3=3&4=d&5=0&6=1&7=4&8=2&9=d 404 (Not Found)

When I console.log(answer._id), I get a reasonable id like 348374831...

Why is it converting the id to a weird format and how can I fix it?

Here seems to be an identical question, although the answer doesn't really explain the problem: AngularJS resource - encoding url string parameter as an array


Solution

  • The corect way to do it is:

    $scope.removeAnswer = function(answer) {
      Answers.remove({
          id: answer._id
     });
    };
    

    or instead of id use the corect name you used in the $resource factory definition. Example:

    var User = $resource('/user/:userId', {userId:'@id'});
    User.get({userId:123}, function(user) {
      user.abc = true;
      user.$save();
    });
    

    $resource expects object parameter. Here's an example in Angular docs