【问题标题】:Can not retrieve route params from a component inside mat-sidenav in Angular无法从 Angular 的 mat-sidenav 内的组件中检索路由参数
【发布时间】:2021-02-13 09:04:44
【问题描述】:

当我将组件放入 ma​​t-sidenav 时,我无法获取路由参数

 this.route.paramMap.pipe(
    tap(params => console.log(params)),  
    switchMap((params: Params) => {
        ...
      })
    ).subscribe(
      ...
    );

【问题讨论】:

  • 你能分享你的路线配置吗?

标签: angular angular-activatedroute mat-sidenav


【解决方案1】:

要从路由器插座外部获取路由,您可以执行以下操作:

    getActivatedRoute(): ActivatedRoute {
        let route = this.router.routerState.root;
        while (route.firstChild) {
            route = route.firstChild;
        }
        return route;
    }

    this.getActivatedRoute().paramMap.pipe(
        tap(params => console.log(params)),  
        switchMap((params: Params) => {
            ...
        })
      ).subscribe(
       ...
    );

【讨论】:

    【解决方案2】:

    尝试将服务写入我的标头(和任何其他组件)可以知道当前的路由和参数。也很高兴知道当前加载的组件,但这并不重要。希望这可行。

       import {Injectable}                              from '@angular/core';
        import {ActivatedRoute, NavigationEnd, Router}   from "@angular/router";
        import {Observable}                              from "rxjs";
        import {first, filter, map, switchMap}           from "rxjs/operators";
        
        @Injectable({providedIn: 'root'})
        export class RouteService {
          constructor(
            private route: ActivatedRoute, 
            private router: Router
          ){}
          public getActivatedRouteParameter(): Observable<any>
          {
            let params
            params = this.router.events.pipe(
              filter(e => e instanceof NavigationEnd),
                map((): ActivatedRoute => {
                  let route = this.route;
                  while (route.firstChild)
                      {
                          route = route.firstChild;
                      }
                  return route;
                }),
                filter((route: ActivatedRoute) => route.outlet === 'primary'),
                switchMap((route: ActivatedRoute) => route.paramMap) , first()
            );
            return params;
          }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-08
      • 2021-01-01
      • 2023-01-31
      • 2021-07-03
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多