我有一个相当简单的ember-cli应用程序(使用Ember 2.2和Ember Data 2.2.1)和一个名为“scenario”的模型。我有一个路由名称'scenario',列出了所有场景。一切正常。在我的应用程序模板中,我有一个导航栏,其中包含一个触发删除所有方案的操作的按钮。我的应用程序控制器代码对于该操作看起来像这样:
this.store.findAll('scenario').then(function(recs){
recs.forEach (function (rec) {
rec.destroyRecord();
});
}, console.log ('findAll Scenario failed'));
当我运行此代码时,console.log始终打印,表示返回的promise未满足。但是情景模型中有明显的记录。我可以在“情景”路线的屏幕上看到它们,也可以在Ember检查员中看到它们。为什么这个'findAll'没有实现?
另外需要注意的一点是:当运行此代码时,Ember Inspector实际上显示了我尝试删除的相同记录。 (例如,如果我分别有2个具有id 23和24的场景,最初我会在Ember Inspector中看到两行符合预期。在此代码运行后,我看到4行,其中两行ID为23,两行ID为24)。但是Ember检查员的“模型类型”栏目仍然说情景(2),仅显示2条记录。任何人都知道发生了什么?
更新(更多信息)
如果我按照以下方式卸载代替'findAll'代码段:
this.store.unload('scenario');
我仍然看到Ember Inspector中的行,但是“MODEL TYPE”列实际上显示了'scenario(0)',并且记录不再显示在'scenario'路线中,这很好。当然,当我刷新时,记录会回来,因为服务器从未被通知删除这些记录。出于某种原因,在'findAll'代码片段后运行上面的'unload'语句无效。
更新(更多信息)
也尝试过:
this.store.findAll('scenario').then(function(recs){
recs.forEach (function (rec) {
Ember.run.once (this, function() {
rec.destroyRecord();
});
});
}, console.log ('findAll Scenario failed'));
同样的错误。
更新
我对console.log调用进行了监督。我按照彼得的建议并将我的代码修改为以下内容:
this.store.findAll('scenario').then(function(recs){
recs.forEach (function (rec) {
Ember.run.once (this, function() {
rec.destroyRecord();
console.log ('found');
});
});
}, function() {
console.log ('findAll Scenario failed');
}
);
此代码验证了findAll确实找到了记录。但最初的问题仍然存在,只是略有不同的症状。我添加了两条记录,然后运行上面的代码。 Ember没有删除这两条记录,而是像以前一样添加了两行; “模型类型”仍显示方案(2)。但是,如果我再次运行相同的代码,“模型类型”转到方案(0),并且在方案路线中不再显示记录。但是这4行仍然留在了灰烬检查员身上。
我认为Ember Data中存在一个错误。但要报告它真的很难。
答案 0 :(得分:1)
您正在使用console.log
语句,直接应该有一个回调函数。因此findAll Scenario failed
将始终执行。
试试这个:
this.store.findAll('scenario').then(
function(recs){
recs.forEach (function (rec) {
Ember.run.once (this, function() {
rec.destroyRecord();
});
});
}, function () { // <-- callback
console.log ('findAll Scenario failed');
}
);
答案 1 :(得分:1)
承诺Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
将两个函数作为参数 - 一个函数将在成功时执行,另一个函数在失败时执行。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
正如Petter所示,您需要将then
放在函数内部。你还可以做的是在控制器上声明两个函数,例如console.log
和didFindScenarios
,并将它们传递给didNotFindScenarios
函数,尽管调用then
很重要如果你想确保他们对应用程序控制器有正确的.bind(this)
引用。
例如,在您的应用程序控制器中:
this