【问题标题】:"undefined" instead of ID in URL on transition in Ember and Ember Data在 Ember 和 Ember 数据中转换时使用“未定义”而不是 URL 中的 ID
【发布时间】:2016-05-12 14:23:38
【问题描述】:

我有一个带有标题和文本字段的非常标准的帖子模型。我有两条模型路线——新路线和显示路线。我想从新路线创建一个帖子,然后过渡到显示路线。

这是我的路由器文件

this.route('post-new', { path: '/posts/new' });
this.route('post-show', { path: '/posts/:postId' });

submit 控制器中的 submit 动作是这样的。

actions: {
  submit() {
    const { title, text } = this.getProperties('title', 'text');
    let post = this.store.createRecord('post', {
      title: title,
      text: text
    });
    post.save().then(() => {
      //success
      this.transitionToRoute('post-show', post);
    }, () => {
      //error
    });
  }
}

所以我希望这会从http://localhost:4200/posts/new 重定向到http://localhost:4200/posts/23 之类的东西(假设23 是id)。
save() 成功并在后端(即 rails)上创建了记录,我还看到使用 Ember Inspector 在浏览器中更新了 post 记录(它现在有一个 ID)。但是重定向发生在http://localhost:4200/posts/undefined

我怎样才能让它在保存后重定向到http://localhost:4200/posts/23 之类的东西?

顺便说一句,版本是:
ember cli:2.3.0-beta.1
余烬:2.3.0
余烬数据:2.3.3


更新

我可以通过替换它来使其工作

this.transitionToRoute('post-show', post);

有了这个

this.transitionToRoute('/posts/' + post.id);

但我希望使用路由名称而不是实际路由路径的解决方案。

【问题讨论】:

  • 你为什么不试试:this.transitionToRoute('post-show', post.id);
  • Asfaik 动态段带下划线:post_id

标签: ember.js ember-data ember-cli


【解决方案1】:

试试:

post.save().then(savedPost => {
  //success
  this.transitionToRoute('post-show', savedPost);
},

【讨论】:

  • post.save().then((savedPost) => { this.transitionToRoute('post-show', savedPost); }); 我试过了。没用。
  • 仍然过渡到未定义? savedPost.get('id') 而不是 savedPost 作为第二个方法参数呢?
【解决方案2】:

你可以在你的路由上实现serialize钩子。

serialize(model) {
  return { postId: model.get('id') };
}

如果您已经拥有模型,这将允许您避免调用模型挂钩。因此,这两个都将按预期工作:

this.transitionToRoute('post-show', post);    // this will NOT call model() hook
this.transitionToRoute('post-show', post.id); // this will call the model() hook

更多信息请访问API docs for Route

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多