Restangular: why does post not update the collection?

Issue

Let’s say I have the following…

myService = Restangular.all('things');
myService.getList().then(
  // success
  function(things) {
      $scope.things = things;
  },
  // failure
  function(things) {
    // do whatever, stuff failed
  }
)

Now I have $scope.things which is a collection of things from the api, all well and good.

I want to post a new thing, and return the promise so I can deal with the pass/fail elsewhere

return $scope.things.post(newThing) // A promise...

However, doing things this way DOESN’T automatically add my new thing to the $scope.things collection. Why not? I’ve seen questions that link to the enhanced promises section of restangular docs and mention the “push” method, but that doesn’t help me because $scope.things has no “push” method.

What’s going on here? Where am I getting confused.

Solution

As mentionned in Restangular docs:

Because Restangular returns promises, we can then call methods on the returned data on promises so that we can run a function after the promise has completed. For instance, after we update a collection, we can then refresh the collection on our scope:

messages.post(newMessage).then(function(newMsg) {
  $scope.messages = messages.getList();
}, function error(reason) {
  // An error has occurred
});

Answered By – user2251745

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.