2017-07-26 62 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)'。我不知道爲什麼,但昨天在我的項目中,它不工作。非常感謝。 –