Open rysilva opened 9 years ago
I've made some progress understanding this, with a few caveats that I've learned.
var listPromise = Restangular.service('users').getList();
...
//Assign the collection to scopes in 2 different ways:
$scopeA.users = listPromise.$object;
listPromise.then(function(users) {
$scopeB.users = users;
});
//Add a new item using enhanced promises:
listPromise.push({name: "John Doe"}).then(function(updatedUsers){
//updatedUsers and $scopeB.users includes the new user, but $scopeA.users does not
});
//Add a new item manually
listPromise.then(function(users) {
users.post({name: "Jane Smith"}).then(function(newUser) {
//newUser includes any updated fields from the server, but it must be manually added to the collection
users.unshift(newUser);
//Again, $scopeB.users will be affected by this, but $scopeA.users will not.
});
});
Two takeaways from this, which may or may not be intended:
listPromise.$object
to be the same as the restangularized collection returned by the promise, so that you don't get out of sync collections. promise.push
does not add the updated object from the server to the collection, so can't be used if the server modifies the object (for instance, adding an id
).So it sounds like I would need to add manually, using double nested callbacks, which isn't so nice. Is there a cleaner way?
The readme page has examples of posting to collections but doesn't appear to have anything about updating the collection after a post to include the new item.
I found a few topics about this including these old answers: https://github.com/mgonto/restangular/issues/113 https://github.com/mgonto/restangular/issues/723
Is this still recommended? It's hard to imagine posting to a collection and not wanting to update the original collection (same with delete).