2016-05-02 32 views
0

我有一个用户JSON API:Emberjs:处理人际关系的最佳方式没有嵌入原有的Json

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

和后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" 
    } 

我也曾在灰烬建立相关模型数据: 应用程序/模型/ user.js的:

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

应用程序/模型/ post.js:

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

我的问题是,我不能从用户对象的烬中访问用户的帖子,即:user.posts是空的。

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

回答

0

灰烬数据并不要求它被嵌入,只要你设置异步为true,像你这样,你应该能够做到无论是访问的帖子在模板中像这样:

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

或在其他地方的烬与javascript,如下所示:

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