【问题标题】:How to fetch data from server for a nested route ember 2.3.0如何从服务器获取嵌套路由 ember 2.3.0 的数据
【发布时间】:2016-02-07 11:47:10
【问题描述】:

我有一个 post 模型和一个 cmets 模型,如下所示:

//  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中的cmets

{#each model as |comment|}}
  <p>{{comment.body}}</p>
{{/each}}
{{outlet}}

我希望当有人点击帖子模板上的 cmets 链接时,在帖子模板的 {{outlet}} 上呈现 cmets 模板。我遇到的问题是获取comments 模型的数据。我在app/routes/post/comments.js 中有一条comments 的路线,它看起来像这样:

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    //I don't know what to do here.
  }
});

我的后端服务器中的 cmets 暴露在 /posts/:post_id/comments 端点上。如何获取 cmets 模板上的 cmets?

【问题讨论】:

    标签: javascript templates ember.js


    【解决方案1】:

    由于您已经在父 route:post 中加载了 Post,因此您的 route:post.comments 可以简单地向它请求 Comments:

    // app/routes/post/comments.js
    import Ember from 'ember';
    
    export default Ember.Route.extend({
      model(){
        const post = this.modelFor('post');
        return post.get('comments');
      }
    });
    

    【讨论】:

    • 当我这样做时,我得到一个错误:GET http://localhost:4200/comments/6 404 (Not Found)GET http://localhost:4200/comments/2 404 (Not Found)Error while processing route: post.comments Adapter operation failed Error: Adapter operation failed
    • 帖子的 cmets 的 API 是否有可能返回 部分 数据,并且在您呈现的模板中,您依赖的字段没有返回在最初的 GET 中?
    【解决方案2】:

    我终于能够完成这项工作。在詹姆斯回答的帮助下,我唯一要做的就是为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);
        }
     }); 
    

    这按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      相关资源
      最近更新 更多