2017-07-26 21 views
1

我使用Ember> = 2.13.x.Ember.js 2,transitionTo在第一级路由中使用多个动态段

我需要使用transitionTo从路由操作中另一条路线走。

这里是演示烬,颤声:https://ember-twiddle.com/3cbb806f31f8d71a6c414452f4fc9ded

我有这种情况:

router.json

Router.map(function() { 
    this.route('home', {path: '/'}); 
    this.route('categories', {path: 'categories'}); 
    this.route('category', {path: ':category_id'}); 
    this.route('posts', {path: 'posts'}); 
    this.route('post', {path: ':category_id/:post_id'}); //I have multiple synamic segments in here 
}); 

路线/ application.js中

actions: { 
    goToPost() { 
     let post = this.store.findRecord('post', 1); 
     this.transitionTo('post', post); 
    } 
} 

路线/ post.js

model(params) { 
    return this.store.findRecord('post', params.id); 
}, 

serialize(model) { 
    console.log('model in serialize():', model); 
    return { category_id: model.get('category.id'), post_id: model.id }; 
} 

模板/ application.hbs

<button type="button" {{action 'goToPost'}}>GoToPost with action (transitionTo)</button> 

所以,当我点击一切正常。

我获取应用动作模型,然后我用this.transitionTo('post', post);

在我的post路线,然后我有serialize(),我现在阅读,当动态片段存在时,它正在使用URL组成。

我的问题:我用正确的方式?

为什么我不能用这样的:this.transitionTo('post', post.category.id, post.id);model()post途径获取模型(从数据库或存储)?

我也试过使用this.transitionTo('post', {category_id: post.category.id, post_id: post.id});,但显然post路由model()不加载任何东西,因为它真的认为对象已经存在。

所以,我只能与serialize()方法解决这个问题。 这是正确的方式吗?

+0

你在你的类别路线有什么? – sheriffderek

+0

重要吗? –

回答

1

你并不需要重写连载钩,默认情况下你会得到路径模型中的参数挂钩的动态段和queryParams。

model({post_id,category_id}) { 
return this.store.findRecord('post', post_id); 
} 

这里是twiddle

this.route('category', {path: 'category/:category_id'}); 
this.route('post', {path: 'post/:category_id/:post_id'}); 

我喜欢添加相应的前缀,像post使URL成为容易distinguisable。

如果你想transitionTo调用模型钩,然后提供对象或者模型参数总是提供所需要的参数可以是字符串或数字。 参考:https://guides.emberjs.com/v2.14.0/routing/defining-your-routes/#toc_dynamic-segments

+0

在你的旋转中你使用'this.transitionTo('post',1,2)'。我改用'this.transitionTo('post',post.get('category.id'),post.id)'。我不知道为什么,但昨天在我的项目中,它不工作。非常感谢。 –