如何使用Ember Data加载嵌套记录(主 - 详细记录)?

时间:2017-01-30 05:46:50

标签: ember.js ember-data

主记录,app / models / account:

import DS from 'ember-data';

export default DS.Model.extend({
  username: DS.attr('string'),
  emailaddress: DS.hasMany('emailaddresses'),
  birthdate: DS.attr('date'),
  gender: DS.attr('boolean')
});

详细记录,app / models / emailaddress:

import DS from 'ember-data';

export default DS.Model.extend({
  account: DS.belongsTo('account'),
  emailaddress: DS.attr('string'),
  verificationcode: DS.attr('string'),
  isverified: DS.attr('string')
});

来自服务器的虚拟JSON字符串:

  

{“id”:0,“username”:“ikevin”,“birthdate”:“2017年1月30日1:34:38   PM”, “性别”:真 “emailaddresses”:[{ “ID”:0, “EMAILADDRESS”: “aaa@bbb.com”, “verificationcode”: “AAAAAA”, “isverified”:假}]} < / p>

适配器/app/adapters/account.js

import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({

  urlForQueryRecord(query) {
    if (query.profile) {
      delete query.profile;
      return `${this._super(...arguments)}/profile`;
    }

    return this._super(...arguments);
  }

});

路线app / route / index.js:

import Ember from 'ember';
import RSVP from 'rsvp';

export default Ember.Route.extend({
  model() {
    return RSVP.hash({
      walletbalance: this.get('store').queryRecord('wallet', {balance: true}),
      instagramfriendscount: this.get('store').queryRecord('instagram', {friendscount: true}),
      accountprofile: this.get('store').queryRecord('account', {profile: true})
    });
  }
});

app / templates / components / account-profile.hbs:

<div class="box">
  <div class="title">Your Profile</div>
  <div>Username: {{account.accountprofile.username}}</div>
  <div>Email Address: {{account.accountprofile.emailaddess}}</div>
  <div>Birthdate: {{account.accountprofile.birthdate}}</div>
  <div>Gender: {{account.accountprofile.gender}}</div>
</div>

我认为这里有两个问题:

  1. 在Chrome Ember插件中,型号类型“emailaddress”的数据始终为0.因此,这意味着它未加载。

  2. 在app / templates / components / account-profile.hbs中,{{account.accountprofile.emailaddess}}未引用正确的字段。注意:目前预计只显示1个电子邮件地址。

  3. 如何解决这些问题以加载和显示嵌套记录?

    谢谢!

1 个答案:

答案 0 :(得分:0)

是的,我自己解决了这个问题:

我将其更改为嵌套数组(如此处指定:http://thejsguy.com/2016/01/29/working-with-nested-data-in-ember-data-models.html

因此从服务器返回的字符串变为:

  

{&#34; id&#34;:0,&#34; username&#34;:&#34; ikevin&#34;,&#34; birthdate&#34;:&#34; 2017年1月30日2点01分14秒   PM&#34;&#34;两性&#34;:真,&#34; emailaddresses&#34;:[{&#34; EMAILADDRESS&#34;:&#34; aaa@bbb.com",& #34; verificationcode&#34;:&#34; AAAAAA&#34;&#34; isverified&#34;:假}]}

在.hbs:

{{1}}

显示电子邮件地址!

谢谢!