Is there better way to get ancestor route params in Angular2?

前端 未结 2 372
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 13:09

I need to get param from route which is not parent and not even grand-parent, it\'s simply somewhere above, along the path to root. I am aware of approaches like shown in An

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 13:33

    I ran into the same problem and after finding this answer I created this function called getParams() that gets all the params of the parents and the current root.

    It combines all the params and reduces into a single map.

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { ServicosService } from '@service/core/servicos.service';
    import { ActivatedRoute } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { map, combineAll } from 'rxjs/operators';
    
    @Injectable()
    export abstract class HttpServiceRouted {
      constructor(
        protected http: HttpClient,
        protected servicos: ServicosService,
        protected route: ActivatedRoute
      ) {}
    
      getParams() {
        return Observable.from(this.route.pathFromRoot.concat(this.route)).pipe(
          map(route => route.params),
          combineAll(),
          map((params: any[]) =>
            params.reduce(
              // tslint:disable-next-line:no-shadowed-variable
              (map: Map, obj) => {
                Object.keys(obj).forEach(key => {
                  map.set(key, obj[key]);
                });
                return map;
              },
              new Map()
            )
          )
        );
      }
    }
    

    Usage:

    this.getParams().subscribe((params: ParamMap) => {
      const id = params.get('id');
    });
    

提交回复
热议问题