mgonto / restangular

AngularJS service to handle Rest API Restful Resources properly and easily
MIT License
7.87k stars 840 forks source link

Best practices for adding to collections #1141

Open rysilva opened 9 years ago

rysilva commented 9 years ago

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).

rysilva commented 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:

So it sounds like I would need to add manually, using double nested callbacks, which isn't so nice. Is there a cleaner way?