2016-03-24 12 views
2

2つの異なるルート設定を、サービス変数値。Angular2:外部値に基づいて特定のルート設定リストの選択性を達成する方法

この節は、外部設定変数の値がtrueの場合、子ルートの1つのリストを使用し、別の場合は2番目のリストを使用します。ルートのパスとレベルは同じです。

例:

親ルート/parent...(非ターミナルルート)、子ルートの設定if service.value is trueで、それが次のルートの設定、他の

@RouteConfig([ 
    {path: '/', component: ChildComponent, name: 'ChildCmp' }, 
    {path: '/test', component: SecComponent, name: 'SecCmp' }, 
    {path: '/tester', component: OptionalComponent, name: 'ThCmp' } 
]) 

それは以下を使用しますservice.value is false場合に使用します:

@RouteConfig([ 
    {path: '/', component: ChildComponent, name: 'ChildCmp' }, 
    {path: '/test', component: SecComponent, name: 'SecCmp' } 
]) 

injectルート設定リストをリストに追加するか、staテンポはservice.valueに基づいていますか?どのようにこのモジュール性やルート設定の選択可能性を達成するためのアイデアですか?

+0

「角度経路設定を動的/実用的に生成するにはどうすればよいですか」(http://stackoverflow.com/questions/35991639/how-do-i-generate-angular-route-configurations-dynamically-pragmatically) –

答えて

3

Router#configを使用すると、経路を動的に設定できるようになります。

だから、ここでは例として取り組んでplnkr

class Child { 
    config = []; 
    constructor(public svc: Service, router: Router) { 
    if(svc.value == 1) { 
     this.config = [ 
     {path: '/', component: ChildComponent, name: 'ChildCmp' }, 
     {path: '/test', component: SecComponent, name: 'SecCmp' }, 
     {path: '/tester', component: OptionalComponent, name: 'ThCmp' }]; 
    } 
    else if(svc.value == 2) { 
     this.config = [ 
     {path: '/', component: ChildComponent, name: 'ChildCmp' }, 
     {path: '/test', component: SecComponent, name: 'SecCmp' } 
     ]; 
    } 

    // Set the config 
    router.config(this.config); 
    } 
} 

を次のように簡単です。値を変更するには、サービスの値を切り替えます。

+0

configを動的にプッシュできることを意味しますか?正しい? – Gary

+1

正確には、この他の[質問](http://stackoverflow.com/a/35997976/4933038)(同様の回答)を参照してください、この他の[質問](http://stackoverflow.com/q/36114571/4933038) –

関連する問題