Restangular插入模型后收集

pfr*_*ied 5 angularjs restangular

我在一个带有post的restangular集合中插入一个模型

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

var item = {
   title : "A title"
};

collection.post(item);
Run Code Online (Sandbox Code Playgroud)

现在我可以做而不是最后一个声明:

collection.post(item).then(function(newItem) {
    collection.push(newItem);
});
Run Code Online (Sandbox Code Playgroud)

为什么插入的模型默认不插入集合中?是否有一个原因?我错过了一个电话或什么的?我想在插入模型后再次避免再次获取集合

Kal*_*yan 1

首先,这两种方法的行为不同:

collection.post(item)- 它向服务器发送 POST 请求但不添加项目添加到集合中,尽管在集合对象上调用 post() 。post() 方法也可用于元素对象。

collection.push(item)- 将项目添加到集合中,但未发送请求没有向服务器如果您希望推迟向服务器发送更新直至采取进一步操作,或者您希望使用服务器上已添加的项目来更新集合以保持集合同步,则可以使用此方法。

如果您想向服务器发送 POST 请求,并向集合添加一个项目而不刷新整个列表,您应该使用下面的代码(与您的问题相同)

collection.post(item).then(function(newItem) {
    collection.push(newItem);
});    
Run Code Online (Sandbox Code Playgroud)


框架设计决策

Why is the inserted model not inserted into the collection by default?
Run Code Online (Sandbox Code Playgroud)

想象一下,如果collection.post(item)collection.push(item)项目添加到集合中,并向服务器发送 POST 请求。如果连接失败或者服务器出错怎么办?无法报告错误或处理错误,并且添加到集合中的数据是不良的陈旧数据并且与服务器不同步。为了避免这种错误,框架强制开发人员仅在 POST 成功时才将项目添加到集合中。

您不仅会在 Restangular 中找到这种编程模型,而且还会在“ng-resource”等类似的 REST 框架中找到这种编程模型。这种编程模型有助于减少错误并确保添加到集合中的项目是合法的,而不是坏的陈旧数据。