[英]How to fetch data from server for a nested route ember 2.3.0
我有一個相關的帖子模型和評論模型,如下所示:
// app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
//....
comments: DS.hasMany('comment'),
//....
})
// app/models/comment.js
import DS from 'ember-data'
export default DS.Model.extend({
//....
ad: DS.belongsTo('post'),,
//....
})
在app/router.js
我有
Router.map(function() {
this.route('post', {path: '/post/:post_id'}, function() {
this.route('comments');
});
)};
我在app/templates/post.hbs
中有一個post
模板,看起來像這樣:
<h2>{{model.title}}</h2>
<p>{{model.body}}</p>
{{#link-to "post.comments"}}
<h2>Comments</h2>
{{/link-to}}
{{outlet}}
我也有一個模板,可在app/templates/post/comments.hbs
呈現app/templates/post/comments.hbs
{#each model as |comment|}}
<p>{{comment.body}}</p>
{{/each}}
{{outlet}}
我想當有人單擊帖子模板上的評論鏈接時,將評論模板呈現在帖子模板的{{outlet}}
上。 我遇到的問題是獲取comments
模型的數據。 我在app/routes/post/comments.js
有一條comments
app/routes/post/comments.js
,它看起來像這樣:
import Ember from 'ember';
export default Ember.Route.extend({
model(){
//I don't know what to do here.
}
});
我的后端服務器中的注釋在/posts/:post_id/comments
端點上公開。 我該如何獲取評論模板上的評論?
由於您已經在父route:post
加載了Post
,因此route:post.comments
可以簡單地route:post.comments
請求Comment
:
// app/routes/post/comments.js
import Ember from 'ember';
export default Ember.Route.extend({
model(){
const post = this.modelFor('post');
return post.get('comments');
}
});
我終於能夠完成這項工作。 在James的幫助下,我唯一要做的就是為CommentAdapter
設置動態名稱空間。 我使用ember生成器生成了一個comment
適配器,並將我的app/routes/post/comments.js
文件更改為如下所示:
// app/routes/post/comments.js
import Ember from 'ember';
export default Ember.Route.extend({
model(){
const post = this.modelFor('post');
this.store.adapterFor('comment').set('namespace', `posts/${post.id}`);
return this.store.query('comment', post.id);
}
});
這按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.