2017-05-03 29 views
1

我有一個路由的Angular 4應用程序。它有這樣的一系列嵌套的路線:如何使用路由來共享Angular 2應用程序的數據?

const routes: Routes = [ 
    { path: "genes/:id", component: GenePageComponent, children: [ 
    { path: "mutations/:mutationType", component: MutationPageComponent }, 
    ]}, 

這讓我參觀/genes/123/mutations/non-coding,這樣的id是123和mutationType是「非編碼」。

如果我注入ActivatedRoute,我可以訂閱urlparams,但只爲片段。這意味着我只能在MutationPageComponent中看到mutationType

由於<router-outlet>無法發出,我怎樣才能將此mutationType參數與其他更高級別的組件(例如側邊欄,搜索欄或其他頂級組件)共享?

同樣,如何將params.idGenePageComponent傳遞給子代MutationPageComponent

+0

您可以從當前的路線得到家長和孩子段參數,可以或者你可以使用一個共享服務,使全球範圍內的可用PARAMS。 –

+0

共享服務可能是我最終要做的。上下走動的孩子看起來就像是脆弱的。 t似乎應該有內置的東西來處理這種情況。 – superluminary

回答

1

您可以通過訪問父組件的航線PARAMS:

this.route.parent.params.subscribe(params => ....); 

你也可以做一個共享服務,其中每個組件更新,它在服務價值爲他人認購。一個基本的例子是這樣的:

import { Injectable } from '@angular/core'; 

import { BehaviorSubject } from 'rxjs/BehaviorSubject'; 


@Injectable() 
export class SharedService { 

    private _sharedDataSource = new BehaviorSubject<MyModel>(<MyModel>{}); 
    sharedData$ = this._sharedDataSource.asObservable(); 

    constructor() { } 

    updateSharedData(data: MyModel) { 
    this._sharedDataSource.next(data); 
    } 

} 

一個BehaviorSubject取默認值,並確保觀察到的總是發出值。組件可以調用updateSharedData函數來更新數據並訂閱sharedData$以在發生更改時獲取更新值。

希望有所幫助。

+0

這是我看過的一個選項。儘管如此,調用'.parent.parent.parent'的想法讓我感到不安。很脆弱。如果我向上或向下移動組件,一切都會中斷。此外,我不能從孩子的父母或父母那裏訂閱孩子的參數,所以如果父母的參數改變,孩子不會知道。 – superluminary

+0

在這種情況下,我認爲您需要使用共享服務來在組件之間共享數據。分層結構中每個級別的組件都需要更新共享服務中的參數值。我可以舉一個例子。 –

1

您可以通過路由器,你提到的

{ path: 'form', component: FormComponent ,data :{data :'Test Data'} }, 

和你的組件

export class FormComponent { 
    sub: any; 
    constructor(private route: ActivatedRoute) { } 
    ngOnInit() { 
     this.sub = this.route 
      .data 
      .subscribe(value => console.log(value)); 
    } 
} 

More Info

但這未必是首選方法,you can use parent child communication or make a service common and share data between them。請查看以下參考資料。

Parent child communication

Share data using service

相關問題