Angular2在路由器出口之外获取路由器参数

Angular2 Get router params outside of router-outlet

我有一个仪表板应用程序,它由一个树视图组件(其中列出了各种内容节点)和一个仪表板编辑组件组成,该组件根据选择的树的哪个分支呈现一些可编辑的内容。

例如树是这样的:

- Football
- - Premier League
- - - Arsenal
- - - Chelsea
- - - ...etc
- - Championship
- - - Derby
- - - ...etc

您单击树中的 'Arsenal',它会在页面上的可编辑面板中呈现该团队的一些内容。

渲染子组件的组件是这样的:

@Component({
    selector: 'my-dashboard',
    template: `
        <div class="tree-panel-container">
            <div class="tree-panel-content">
                <content-tree [startNodeId]="startNodeIdContent"></content-tree>
            </div>
        </div>
        <router-outlet></router-outlet>
    `,
    directives: [
        ContentTreeComponent, 
        ContentDashboardComponent, 
        RouterOutlet
    ],
    providers: [
        HTTP_PROVIDERS
    ]
})

可编辑内容呈现在 router-outlet 中,因此每个可编辑内容都有其独特的 URL,例如例如,example.com/content/edit/123 其中 123 是阿森纳内容的 ID。

一切正常。

但是,我想要做的是能够访问 content-tree 组件中的 id 路由参数。目前,我很确定我在该组件中的代码 应该 工作:

import {Component, Input, OnInit}   from '@angular/core';
import {Router, RouteParams}        from '@angular/router-deprecated';

import {ContentNode}                from './content-node';
import {ContentService}             from '../services/content.service';


@Component({
    selector: 'content-tree',
    directives: [ContentTreeComponent],
    template: `
        <ol class="tree">
            <li *ngFor="let contentNode of contentNodes" class="tree__branch" [ngClass]="{'tree__branch--has-children': contentNode.HasChildren}">
                <a *ngIf="contentNode.HasChildren" (click)="contentNode.toggle=!contentNode.toggle" class="tree__branch__toggle">
                    {{ !!contentNode.toggle ? '-' : '+' }}
                </a> 
                <a class="tree__branch__link" (click)="onSelect(contentNode)">{{ contentNode.Name }}</a>
                <content-tree *ngIf="contentNode.toggle" [startNodeId]="contentNode.Id"></content-tree>
            </li>
        </ol>
        <div class="error" *ngIf="errorMessage">{{errorMessage}}</div>
    `
})
export class ContentTreeComponent implements OnInit {

    constructor(
        private _contentService: ContentService,
        private _router: Router,
        private _routeParams: RouteParams
    ) { }

    errorMessage: string;

    @Input('startNodeId')
    private _startNodeId: number;

    contentNodes: ContentNode[];

    ngOnInit() { 
        let nodeId = +this._routeParams.get('id');
        console.log('nodeId = ' + nodeId);
        this.getContentNodes();
    }

    onSelect(contentNode: ContentNode) {
        this._router.navigate( ['ContentEdit', { id: contentNode.Id }]  );
    }

    getContentNodes() {
        this._contentService.getContentNodes(this._startNodeId)
            .subscribe(
                contentNodes => this.contentNodes = contentNodes,
                error =>  this.errorMessage = <any>error
            );
    }
}

但是 ngOnInit 方法中的 nodeId 变量总是返回为 0.

问题: 是否只能访问路由器插座呈现的组件中的路由参数?如果是这样,那么处理此问题的最佳方法是创建第二个(命名,因为现在将有 2 个)路由器插座吗?如果不是,那我哪里做错了?

非常感谢。

编辑:

现在已经生成了一个有效的(而且非常丑陋;))Plnkr 来展示应用程序的基础知识:http://plnkr.co/edit/W3PVk3Ss5Wq59IbnLjaK?p=preview。查看评论以了解应该发生的事情...

Is it only possible to access route params in a component rendered by a router-outlet?

是的,<router-outlet></router-outlet> 告诉 Angular2 将包含组件视为 "routing" 组件。因此,您无法将 RouteParams 实例注入到 class 中,因为它不是通过路由指令实例化的。

If not, then what am I doing wrong?

我不会说你做错了什么,你只是对它的设计有误解。我也有这个最初的误解。我发现 this Angular2 文章是了解如何传递数据以及如何在父子组件之间进行通信的重要来源。


在您的具体情况下,我建议从 ContentTreeComponentconstructor 中删除 RouteParams,因为它只有在从 "routing" 组件呈现时才可用。

export class ContentTreeComponent implements OnInit {

    constructor(
        private _contentService: ContentService,
        private _router: Router
    ) { }

    // Omitted for brevity...
}

然后为了获得 id,您可能需要分享更多的顶级代码,以便我可以看到它的来源...

在新路由器中 (>= RC.0 <=RC.2) 这将是

  import 'rxjs/add/operator/first';
  ...

  constructor(private router:Router, private routeSerializer:RouterUrlSerializer, private location:Location) {
    router.changes.first().subscribe(() => {

    let urlTree = this.routeSerializer.parse(location.path());
      console.log('id', urlTree.children(urlTree.children(urlTree.root)[0])[0].segment);
    });
  }

另见

从angular 2.1.0 和 Router 3.1.0

中的组件外部获取活动路由

我找到了一种很好的方法,可以从应用程序内的任何位置获取显示路线中的所有参数、queryParmas、段和片段。只需将此代码添加到您需要的任何组件,或创建一个可以在整个应用程序中注入的服务。

import { Router, NavigationEnd } from "@angular/router";
import { Component, OnInit } from '@angular/core';

...

export class MyComponentOrService implements OnInit {

constructor(private router: Router) {}

ngOnInit() {

  /* this subscription will fire always when the url changes */
  this.router.events.subscribe(val=> {

    /* the router will fire multiple events */
    /* we only want to react if it's the final active route */
    if (val instanceof NavigationEnd) {

     /* the variable curUrlTree holds all params, queryParams, segments and fragments from the current (active) route */
     let curUrlTree = this.router.parseUrl(this.router.url);
     console.info(curUrlTree);
    }
  });
}
...

由于在此 post 中找到的解决方案无法解决我的问题,我刚刚添加了一个目前可以修复或帮助您处理此类问题的其他解决方案其他 post 有类似问题:Angular 2: How do I get params of a route from outside of a router-outlet

这个解决方案对我有用:complete example

constructor(
  private readonly router: Router,
  private readonly rootRoute: ActivatedRoute,
){
  router.events.pipe(
    filter(e => e instanceof NavigationEnd),
    map(e => this.getParams(this.rootRoute))
  ).subscribe(params => {
   //
  });
}

private getParams(route: ActivatedRoute): Params {
  // route param names (eg /a/:personId) must be ditinct within
  // a route otherwise they'll be overwritten
  let params = route.snapshot.params
  params = { ...route.snapshot.queryParams, ...params}
  if(route.children){
    for(let r of route.children){
      params = {...this.getParams(r), ...params};        
    }
  }
  return params;
}

感谢 Toxicable