Pete Tinkler Pete Tinkler - 5 months ago 35
AngularJS Question

Restangular: why does post not update the collection?

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.

Answer

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
});