Angular 2: getting RouteParams from parent component

前端 未结 13 910
暖寄归人
暖寄归人 2020-11-28 04:47

How do I get the RouteParams from a parent component?

App.ts:

@Component({
  ...
})

@RouteConfig([
  {path: \'/\', component: HomeCompo         


        
13条回答
  •  醉梦人生
    2020-11-28 05:01

    You can do it on the snapshot with the following, but if it changes, your id property will not be updated.

    This example also shows how you can subscribe to all ancestor parameter changes and look for the one you are interested in by merging all of the parameter observables. However, be careful with this method because there could be multiple ancestors that have the same parameter key/name.

    import { Component } from '@angular/core';
    import { ActivatedRoute, Params, ActivatedRouteSnapshot } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { Subscription } from 'rxjs/Subscription';
    import 'rxjs/add/observable/merge';
    
    // This traverses the route, following ancestors, looking for the parameter.
    function getParam(route: ActivatedRouteSnapshot, key: string): any {
      if (route != null) {
        let param = route.params[key];
        if (param === undefined) {
          return getParam(route.parent, key);
        } else {
          return param;
        }
      } else {
        return undefined;
      }
    }
    
    @Component({ /* ... */ })
    export class SomeChildComponent {
    
      id: string;
    
      private _parameterSubscription: Subscription;
    
      constructor(private route: ActivatedRoute) {
      }
    
      ngOnInit() {
        // There is no need to do this if you subscribe to parameter changes like below.
        this.id = getParam(this.route.snapshot, 'id');
    
        let paramObservables: Observable[] =
          this.route.pathFromRoot.map(route => route.params);
    
        this._parametersSubscription =
          Observable.merge(...paramObservables).subscribe((params: Params) => {
            if ('id' in params) {
              // If there are ancestor routes that have used
              // the same parameter name, they will conflict!
              this.id = params['id'];
            }
          });
      }
    
      ngOnDestroy() {
        this._parameterSubscription.unsubscribe();
      }
    }
    

提交回复
热议问题