2016-02-29 73 views
1

我试图在我的烬应用程序中构建一个动态REST调用。我试图使用这个解决方案作为一个起点,但它不工作,我不知道是否因为Ember现在使用JSON API并且我构造错了: Dynamic segment in ember data adapter与JSON链接有很多关系

在后端呼叫貌似/posts/{postID}/comments,我希望能够从ID 1,2,3,等后动态获取评论...

这里是我的基本结构
Post模型:

export default DS.Model.extend({ 
    name: DS.attr('string'), 
    comments: DS.hasMany('comment', {async:true}) 
}); 

评论模型:

export default DS.Model.extend({ 
    name: DS.attr('string') 
}); 

模板:

<ul> 
    {{#each model as |post|}} 
    {{#each post.comments as |comment|}} 
     <li>{{comment.name}}</li> 
    {{/each}} 
    {{/each}} 
</ul> 

的Json POST负载:

"data": [{ 
    "type": "posts", 
    "id": "1", 
    "attributes": { 
     "id": 1 
     "name": "my title" 
    }, 
    "links": { 
     "comments": "comments" 
    } 
    }] 

我的目标是使该呼叫的意见,构建一个命名空间,看起来像/posts/1/comments使用上面的模板。我得到后期模型,并验证了第一个{{#each}}循环的工作原理,但对post.comments的调用在模板中没有任何作用。

+0

它看起来像你缺少'belongsTo' https://guides.emberjs.com/v2.3.0/models/relationships/#toc_one-to-many –

+0

这并没有造成差异 – PlainPat

+0

是否有已经有答案了? –

回答

0

这是假设您有权更改有效负载响应。如果没有,你将不得不使用串行器来处理数据。

首先,从您在此显示的内容看,您看起来并没有将任何评论加载到模型中。

你的有效载荷或许应该是这个样子:

"data": [{ 
    "type": "posts", 
    "id": "1", 
    "attributes": { 
    "id": 1 
    "name": "my title" 
    }, 
    "relationships": { 
    "comments": { 
     "data": [ 
     { 
      "id": "3", 
      "name": "comment" 
     } 
     ] 
    } 
    } 
}] 
+2

这工作,但没有完成我想要做的事情。访问这些数据最终将调用数据数组中每个注释ID的后端。我正在寻找一个电话来获得我所有的评论。而不是'/ post/1/comments/1'我想要'/ post/1/comments',根据我的理解,应该使用links属性 – PlainPat

2

您的有效载荷不能确认JSON API。由于commentspost的关系,有效载荷应该是这个样子:

"data": [{ 
    "type": "posts", 
    "id": "1", 
    "attributes": { 
    "id": 1, 
    "name": "my title" 
    }, 
    "relationships": { 
    "comments": { 
     "links": { 
     "related": "/posts/1/comments" 
     } 
    } 
    } 
}] 

here了解有关JSON API关系的更多信息。


N.B.你的有效载荷的构建方式,与旧的RESTSerializer一起工作。