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"
};
collection.post(item);
Now i could do instead of the last statement:
collection.post(item).then(function(newItem) {
collection.push(newItem);
});
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:
collection.post(item)
- 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)
collection.post(item).then(function(newItem) {
collection.push(newItem);
});
Framework Design Decision
Why is the inserted model not inserted into the collection by default?
Imagine if collection.post(item)
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.