Angular 2新路由器:如何获取子组件的路由器参数?

问题描述 投票:14回答:6

@angular/router 3.0.0-rc.1的最新版本中,您从URL /路由获取参数的方式已更改。

基于this文档,您应该能够通过订阅参数获得参数,但在我的情况下,它似乎无法正常工作。

我想要实现的是将params放入我的父组件FROM子路由。

例如,假设这是我的路线:

const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
    pathMatch: 'prefix',
    children: [
      {
        path: ':id',
        component: ChildComponent
      }
    ]
  }
];

我想获取id参数并在我的ParentComponent中使用它。所以我这样做:

export class ParentComponent implements OnInit {

  sub: any;
  constructor(
    private route: ActivatedRoute) {
    this.route = route;
   }

  ngOnInit() {

    this.sub = this.route.params.subscribe(params => {
     let id = params['id'];
     console.log(id);
   });

  }

}

像这样我得到:

未定义

我在这里错过了什么?

angular typescript rxjs angular2-routing
6个回答
26
投票

ActivatedRoute有getter访问其父/子路由信息。

要从父级访问第一个子路由,您将使用:

this.route.firstChild.params

如果您想要所有子路线,您将使用children属性。这将返回一个ActivatedRoute数组

this.route.children

如果您在子路线中并且需要来自父母的参数:

this.route.parent.params


5
投票

子参数与子ActivatedRoute关联/存储。它们在父级的ActivatedRoute上不可用。因此,您首先需要使用getter firstChildchildren来获取孩子的ActivatedRoute。

然后,父级可以订阅子参数更改:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute }               from '@angular/router';
import { Subscription }                 from 'rxjs/Subscription';

export class ParentComponent implements OnInit, OnDestroy {
   private sub: Subscription;
   constructor(private route: ActivatedRoute) {}
   ngOnInit() {
      this.sub = this.route.firstChild.params.subscribe(
        params => console.log(params.id));
   }
   ngOnDestroy() {
      this.sub.unsubscribe();
   }
}

或者它可以获取子参数的快照:

import { Component }      from '@angular/core';
import { ActivatedRoute } from '@angular/router';

export class ParentComponent {
   constructor(private route: ActivatedRoute) {}
   someMethod() {
      console.log(this.route.firstChild.snapshot.params.id);
   }
}

如果您想要获得所有孩子(例如,如果您有多个出口),请使用ActivatedRoute.childrenActivatedRouteSnapshot.children获取一系列子ActivatedRoutes或子ActivatedRouteShapshots。


3
投票

通过ActivatedRoute获取子参数非常容易,但是如果更改当前子项,则可以快速遇到问题。

首先是几个笔记:

  • activatedRoute.firstChild属性是ActivatedRoute实例,而不是可观察的。
  • 另请注意,activatedRoute.paramMap是一个可观察的。

以下是您遇到问题的方法:

  • 考虑具有两个子路由的组件 - 以及相应的组件 - 其中一次只显示一个(例如,选项卡式界面)。
  • 如果您在firstChild.paramMap处理程序中访问ngOnInit,您将能够订阅它并在更改时监视参数。这看起来和工作都很好。
  • 如果切换到第二个选项卡然后回到第一个选项卡将会中断。这是因为您最初在不再存在的ActivatedRoute实例上订阅了paramMap
  • 重要提示:如果您尝试访问孩子的paramMap,这只是一个问题。如果您正在尝试访问“自己的”paramMap,或者子组件也注入了paramMap,那么一切都会好的。

我发现的最干净的解决方案如下:

注意:除了router: Router之外,首先注入route: ActivatedRoute

const firstChildParams$ = this.router.events.pipe(filter(e => e instanceof NavigationEnd),
                                                  startWith(undefined),
                                                  switchMap(e => this.route.firstChild!.paramMap));

这样做只会侦听NavigationEnd事件,之后会有一个新的firstChild。通过使用switchMap,您无需担心取消订阅旧的冗余地图。也不是从不使用导航事件的实际值,并且需要startWith才能在第一次立即处理参数。

我一直在收集这样的有用的东西到我可以在任何地方注入的RouterHelperService,而不必记住所有这些疯狂。


有一天,我可能会建议应该有一个可观察到的等效的firstChild,那么这不会是一个问题。然而,它可能会在其他场景中引入更多混乱!


1
投票

通过使用this.activatedRoute.snapshot.firstChild.params


1
投票
this.route.snapshot.paramMap.get('id');

0
投票
  this.router.events.subscribe(event => {
            if (event instanceof RoutesRecognized) {
                // let strId = event.state.root.firstChild.children[0].data;
                let a = event.state.root.firstChild.children.map((route) => {
                    while (route.firstChild) {
                        route = route.firstChild;
                    }

                    return route;
                });
                console.log('Title', a[0].data.title);
                this.meta.updateTitle(a[0].data.title);
            }
            if (event instanceof NavigationEnd) {
                (<any>window).gtag('config', this.googleAnalyticsCode, {
                    'page_title' : this.titleService.getTitle(),
                    'page_path': event.urlAfterRedirects
                });
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.