在我的控制器中我有开放动作。此动作应删除所有模型记录,然后发送ajax请求并获取新模型并替换模型。我的余烬数据适配器是LSA
OlapApp.OpenController = Ember.Controller.extend({
needs: ['application'],
actions: {
open: function() {
var self = this;
var xhr = $.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'http://localhost:9095/service.asmx/getModel',
data: '{}',
success: function(response) {
//Success Empty AxisModel;
var data = JSON.parse(response.d);
self.store.findAll('axisModel').then(function(items) {
console.log('try to delete');
items.forEach(function(item) {
item.deleteRecord();
item.save();
});
});
setTimeout(function() {
//Fill Axis Model
_.each(data.axisModel, function(v, i) {
var record = self.store.createRecord('axisModel', {
id: v["id"],
uniqueName: v["uniqueName"],
name: v["name"],
hierarchyUniqueName: v.hierarchyUniqueName,
type: v["type"],
isMeasure: v.isMeasure,
orderId: v.orderId,
isActive: v.isActive,
isAll: v.isAll,
sort: v.sort
});
record.save();
});
self.get('controllers.application').send('showNotification', 'Open', 'success');
}, 2000);
}
});
}
}
});
但是当我尝试创建新模型时,我收到此错误:
Assertion failed: The id a12 has already been used with another record of type OlapApp.AxisModel.
Assertion failed: The id a13 has already been used with another record of type OlapApp.AxisModel.
解
最后我找到了解决方案。修复此问题只需在Ember.run.once中包装deleteRecord(),如下所示:
self.store.findAll('axisModel').then(function(items) {
items.forEach(function(item){
Ember.run.once(function(){
item.deleteRecord();
item.save();
});
});
});
答案 0 :(得分:2)
对于删除记录,使用 forEach 会出现问题,因为查找商店的结果是实时数组。您可以在GitHub https://github.com/emberjs/data/issues/772中看到此讨论。您可以使用toArray()来生成实时数组的静态副本
self.store.findAll('axisModel').then(
function(items) {
items.toArray().forEach(function(item){
item.deleteRecord();
item.save();
});
});