2017-05-03 51 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

相关问题