Search code examples
restangular

Using save or put with Restangular results in "undefined" being included in URL


I am using Restangular to download an object, update it and then attempt to save back to the server using the save method. Here is the code that retrieves the object:

Restangular.one("survey", surveyID).getList().then (
  function (response) {
    $scope.survey = response[0];
  }
);

This sets $scope.survey to a properly "restangularized" object, with the fields that come back from the GET request, along with the methods like save, put, etc.

If I then invoke the following function after making some edits to the $scope.survey object:

$scope.saveChanges = function () {
  $scope.survey.save();
};

restangular tries to use the URL /survey/1/undefined for the PUT request (1 is the correct ID for the object).

My survey object doesn't have an id field (it's surveyID instead), and so I suspected this might be the problem. However, replacing the surveyID field with an id field changed the URL to be /survey/1/undefined/1

I have stripped down the object returned by the GET request to be just primitives, and this does not change the situation.

Why is the incorrect route being generated?


Solution

  • II discovered the problem was actually with the REST service; when called with GET /surveys/1, it was returning an array with a single object in it, rather than returning the object itself.

    I think this caused restangular to think that a collection was being accessed (note that I was having to call getList rather than get in order to get a properly restangularized object).