问题描述
我要在带有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"
};
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)
-它将POST请求发送到服务器,但不添加项到集合中,尽管在集合对象上调用了post(). post()方法也可用于元素对象.
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)
-将项目添加到集合中,但未发送请求到服务器.如果要推迟将更新发送到服务器,直到进一步采取措施,或者要使用服务器上已添加的项目更新集合以保持集合同步,请使用此方法.
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.
如果您要向服务器发送POST请求,并且还想在不刷新整个列表的情况下向集合中添加项目,则应使用以下代码(与您的问题相同)
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);
});
Why is the inserted model not inserted into the collection by default?
想象一下,如果collection.post(item)
和collection.push(item)
将项目添加到集合中,并且还将POST请求发送到服务器.如果连接失败或服务器出现错误怎么办?无法报告错误或处理错误,并且添加到集合中的数据是陈旧数据,并且与服务器不同步.为了避免此类错误,该框架强制开发人员仅在POST成功的情况下才将项目添加到集合中.
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.
您不仅会在Restangular中找到这种编程模型,而且还会在类似的REST框架(如"ng-resource")中找到该编程模型.这种编程模型有助于减少错误,并确保添加到集合中的项目是合法的,并且不是不良的陈旧数据.
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.
这篇关于在发布后将矩形插入模型以进行收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!