Restangular inserting models to collection after post


I am inserting a model in a restangular collection with post

var collectionService = restAngular.all('collection');
var collection = collectionService.getList();

var item = {
   title : "A title"

Now i could do instead of the last statement: {

Why is the inserted model not inserted into the collection by default? Is there a reason for this? Am i missing a call or something? I would like to avoid fetching the collection again after i inserted the model


Firstly, the behavior for the two methods are different: – It sends a POST request to the server but doesn’t add item to the collection although post() is being called on collection object. The post() method is also available on an element object.

collection.push(item) – Adds the item to the collection but no request sent to the server. You use this method if you want to defer sending update to the server until further action or if you want to update the collection with an already added item on the server in order to keep the collection sync.

If you want to send a POST request to the server and also add an item to the collection without refreshing the whole list, you should use the below code (same as in your question) {

Framework Design Decision

Why is the inserted model not inserted into the collection by default?

Imagine if and collection.push(item) adds item into collection and also sends a POST request to the server. What if the connection fails or the server error out? There is no way to report the error or to handle the error and the data added to collection is a bad stale data and out of sync with server. In order to avoid this kind of bug, the framework force the developers to add the item into collection only if the POST is successful.

You will find this programming model not only in Restangular but also in similar REST frameworks like ‘ng-resource’. This programming model helps to reduce the bug and ensure that the item added to the collection is legitimate and not a bad stale data.

Answered By – Kalyan

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.