【问题标题】:Emberjs: Best way to handle relationships not embedded in original JsonEmberjs:处理未嵌入原始 Json 的关系的最佳方法
【发布时间】:2016-05-02 15:12:13
【问题描述】:

我有一个用户 JSON api:

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    }
}

和一个 post JSON api:

{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  }

我还在 Ember Data 中创建了相关模型: 应用程序/模型/user.js:

export default Model.extend({
  name: attr('string'),
  username: attr('string'),
  email: attr('string'),
  posts: hasMany('post', { async: true })
});

app/models/post.js:

export default Model.extend({
  title: attr('string'),
  body: attr('string'),
  userId: belongsTo('user')
});

我的问题是,我无法从 ember 中的用户对象访问用户的帖子,即:user.posts 为空。

处理此问题的最佳方法是什么? Ember Data 是否需要将关系嵌入到 JSON 中?或者,我可以从一个组件(我有一个组件来显示用户的所有帖子)中将帖子与商店分开调用吗?

【问题讨论】:

    标签: json ember.js ember-data


    【解决方案1】:

    Ember 数据不需要嵌入它,只要您将 async 设置为 true,就像您所做的那样,您应该能够像这样访问模板中的帖子:

    // template.hbs
    {{#each user.posts as |post|}}
      {{post.title}}
    {{/each}}
    

    或者在其他地方用 javascript 在 ember 中,像这样:

    this.get('store')
    .findRecord('user',1)
    .then((user)=> {
        return user.get('posts')
    })
    .then((posts)=> {
        console.log(posts)
        //use posts here
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 2021-12-10
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多