How do I use Routing to share data around an Angular 2 application?

狂风中的少年 提交于 2019-12-11 08:39:41

问题


I have a routed Angular 4 application. It has a series of nested routes like this:

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

This lets me visit /genes/123/mutations/non-coding, so that id is 123 and mutationType is 'non-coding'.

If I inject ActivatedRoute, I can subscribe to the url or params, but only for the fragment. This means that I can only see mutationType in the MutationPageComponent.

Given that <router-outlet> can't emit, how can I share this mutationType parameter with other higher level components, for example, a sidebar, searchbar, or other top level components?

Likewise, how can I pass params.id from the GenePageComponent into the child MutationPageComponent?


回答1:


You can access the parent component's route params with:

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

You can also do a shared service where each component updates it's value in the service for others to subscribe to. A basic example would look like this:

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);
  }

}

A BehaviorSubject takes a default value and ensure that the observable always emits a value. Components can call the updateSharedData function to update data and subscribe to sharedData$ to get updated value when something changes.

Hope that helps.




回答2:


You can pass through router as you mentioned

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

and your component

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

More Info

But this may not be the preferred way, you can use parent child communication or make a service common and share data between them. Check below references for doing that.

Parent child communication

Share data using service



来源:https://stackoverflow.com/questions/43758681/how-do-i-use-routing-to-share-data-around-an-angular-2-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!