【问题标题】:How do I get access to route parameters in angular 2.0 from components not mapped to a route/router-outlet如何从未映射到路由/路由器出口的组件中访问 Angular 2.0 中的路由参数
【发布时间】:2017-05-07 05:30:23
【问题描述】:

我有以下路由

const routes: Routes = [
    { path: 'metadata/:path', component: MetadataDisplayComponent },
    { path: 'data/:path', component: DataDisplayComponent }
]

这是我的 AppComponent,其中注入了元数据/数据显示组件。

@Component({
    selector: 'my-app',
    template: `
        <tree-view></tree-view>  <!-- a component the displays a tree like hierarchy of the path -->
        <router-outlet></router-outlet>
    `
})

所以本质上,我总是希望树视图在那里做它的事情,而不管元数据/数据状态如何,但我需要根据我的路由中的参数对其进行初始化。

现在,我的问题是我的“树视图”组件需要访问我在 2 条路由中定义的变量“:path”。当我尝试以下(在我的树视图组件内)

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

@Component({
    selector : 'tree-view',
    // etc...
})

export class TreeViewComponent implements OnInit {

    private sub: any;

    contstructor(
        @Inject(ActivatedRoute) private route: ActivatedRoute
    ) {}

    ngOnInit(): void {
        this.sub = this.route.params.subscribe(params => {
            console.log(params['path']);    // this logs "undefined"
        });
    }

    // added this as per the suggestion in the comments
    ngAfterViewInit(): void {
        this.sub = this.route.params.subscribe(params => {
            console.log(params['path']);    // this logs "undefined"
        });
    }

    // etc... 

}

我尝试访问“路径”参数不成功,它被控制台记录为“未定义”。

当我在 MetadataDisplayComponent 中尝试完全相同的 ngOnInit 时,我能够 console.log 路径没有问题。

我几乎可以肯定,这是因为我的 TreeViewComponent 没有与我的一条路由关联,因此无法访问路由变量。它位于路由器插座旁边,但不在路由器插座内。

有什么办法可以解决这个问题吗?我意识到我可能以完全愚蠢的方式规划了布局,并愿意接受建议。

【问题讨论】:

  • 如果您将 ActivatedRoute 注入变量 this.route,您的代码不会显示。你在做这个吗?
  • 是的,我是。我试图尽可能多地删减代码,以突出问题。我的路由在我的 MetadataDisplayComponent 中使用完全相同的设置,所以我至少做了那么多工作。
  • 尝试将您的订阅移动到 ngAfterViewInit()。
  • 刚试了,还是未定义
  • 不确定为什么需要这个:@Inject(ActivatedRoute)

标签: angular routing angular2-routing angular-components


【解决方案1】:

经过几个小时搜索相同的东西,这是有效的

在路由器出口外的服务/组件内

this.router.events.subscribe(val => {
      if (val instanceof NavigationEnd) {

        let r = this.route;
        while (r.firstChild) {
          r = r.firstChild;
        }
        r.params.subscribe(params => {
          //do stuff with params['yourParam']
          console.log(params);
        });
      }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-25
    • 2016-04-14
    • 2018-09-12
    • 2023-03-12
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多