【问题标题】:Ember Data findAll() not populating models?Ember Data findAll() 不填充模型?
【发布时间】:2013-05-23 14:40:40
【问题描述】:

ember js 新手,正在使用 ember-data 开发应用程序。如果我使用 FixtureAdapter 使用相同的数据进行测试,则所有内容都可以填充到 html 模板中。当我切换到 RESTAdapter 时,数据看起来恢复正常,但模型没有填充到模板中?有任何想法吗?代码如下:

App.Store = DS.Store.extend({
  revision:12,
  //adapter: 'DS.FixtureAdapter'
  adapter: DS.RESTAdapter.extend({
    url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
  })
});

App.Brand = DS.Model.extend({
  name: DS.attr('string'),
  numStyles: DS.attr('string'),
  vendorId: DS.attr('string')
});

App.BrandsRoute = Ember.Route.extend({
  setupController:function(controller){
  },
  model:function(){
    return App.Brand.find(); 
  }
});

这是返回的数据,但没有插入到模板中!

 returnValue: [{numStyles:1, name:Easton, vendorId:6043}, {numStyles:1, name:Louisville     Slugger, vendorId:6075},…]
0: {numStyles:1, name:Easton, vendorId:6043}
1: {numStyles:1, name:Louisville Slugger, vendorId:6075}
2: {numStyles:1, name:Rawlings, vendorId:6109}
3: {numStyles:7, name:BWP Bats , vendorId:6496}
4: {numStyles:1, name:DeMarini, vendorId:W002}
status: "ok"

这是模板:

{{#each brand in model.returnValue }}
  <div class="brand-node"{{action select brand}}>
    <h2>{{brand.name}}</h2>
    <p>{{brand.numStyles}} Styles</p>
  </div>
{{/each}}

任何帮助将不胜感激!我没有收到任何错误,数据似乎恢复正常,只是没有进入模板。不确定返回的数据集是否需要“id”参数?

我还使用 Store config 将 find() 从复数更改为单数:

 DS.RESTAdapter.configure("plurals", {
   brand: "brand"
 });

API 的编写方式,它所期望的“品牌”而不是“品牌”......也许与此有关??

提前致谢。

【问题讨论】:

    标签: json ember.js ember-data


    【解决方案1】:

    你说过:

    不确定返回的数据集是否需要“id”参数?

    是的,您猜对了,从后端返回的数据需要一个 id 字段集。如果 id 字段名称不同,那么 id 你也应该像这样在 ember 中定义它:

    App.Store = DS.Store.extend({
      revision:12,
      //adapter: 'DS.FixtureAdapter'
      adapter: DS.RESTAdapter.extend({
        url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
      }),
      serializer: DS.RESTSerializer.extend({
        primaryKey: function (type) {
          return '_my_super_custom_ID'; // Only needed if your id field name is different than 'id'
        }
      })
    });
    

    我想你的 Fixtures 定义了一个 id,因此它可以工作,对吧?

    注意:您根本不需要明确定义id 字段,ember 会自动将id 字段添加到模型中,因此您的模型是正确的。

    这里是 website,它仍然是 WIP,但可以作为此约定的很好参考 并如那里所述:

    文档必须包含一个 id 键。

    这就是您的 JSON 对于记录集合的外观:

    {
      "brands": [{
        "id": "1", 
        "numStyles": "1", 
        "name": "Easton", 
        "vendorId" :"6043"
      }, {
        "id": "2", 
        "numStyles": "4", 
        "name": "Siemens", 
        "vendorId": "6123"
      }/** and so on**/]
    }
    

    注意: 如您所见,JSON 根称为 returnValue,如果您不适应复数形式,则应称为 brandbrands。请参阅 here 以获取我正在谈论的 JSON 根的参考。

    希望对你有帮助

    【讨论】:

    • 太棒了,感谢您的回复。我还注意到,我需要在返回时“强调”模特 atts,我们以前是驼峰式的。再次感谢您的回复!
    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2013-11-22
    • 1970-01-01
    相关资源
    最近更新 更多