How do I use Routing to share data around an Angul

2019-07-26 14:04发布

问题:

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