如何在对ember数据模型进行通用查找后劫持promise解析

How to hijack the promise resolution after a generic find on an ember-data model?

本文关键字:查找 劫持 解析 promise ember 数据模型      更新时间:2023-09-26

我需要手动检查从基本查找返回的ember数据模型(该模型不绑定到模板,相反,我需要动态应用一些逻辑)

到目前为止,我已经尝试了以下(没有运气)

App.Foo.find().then(function(model) {
  console.log("here with the ember-data payload");
  console.log(model.get('length'));
}, function(error) {
  console.log("broken");
});

成功块确实启动了,但它似乎总是返回0个结果,但当我在chrome中查看网络选项卡时,它显示了一个有效的json负载,该负载在我使用的这个promise钩子之外工作。

有可能用ember数据版本11劫持promise决议吗?

App.Foo.find()返回模型列表,即DS.AdapterPopulatedRecordArray,它是而不是数组,因此没有长度属性。但它有一个内容属性,即模型数组。因此,在您的示例中,您应该使用console.log(model.content.length);使其工作:

App.Foo.find().then(function(result) {
  console.log("here with the ember-data payload");
  console.log(result.content.length);
  console.log(result.objectAt(0));
}, function(error) {
  console.log("broken");
});

请注意,不能在DS.AdapterPopulatedRecordArray上使用[]运算符,因为它不是数组。请参阅DS上的Ember指南。您应该使用objectAtresult.objectAt(0);

App.Model.find().then(function(notes) {console.log(notes.content.length)})为我返回了5,这是我的应用程序的正确返回值。

我认为您的语法是正确的,尽管您可能对服务器返回的数据有问题?也许由于某种原因,它没有序列化为实际记录。可能值得仔细检查。