Angular2 在路由器插座之外获取路由器参数 [英] Angular2 Get router params outside of router-outlet

查看:30
本文介绍了Angular2 在路由器插座之外获取路由器参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如树是这样的:

- 足球- - 超级联赛- - - 阿森纳- - - 切尔西- - - ...等等- - 冠军- - - 德比- - - ...等等

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

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

@Component({选择器:我的仪表板",模板:`<div class="tree-panel-container"><div class="tree-panel-content"><content-tree [startNodeId]="startNodeIdContent"></content-tree>

<路由器插座></路由器插座>`,指令:[内容树组件,内容仪表板组件,路由器插座],供应商: [HTTP_PROVIDERS]})

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

这一切正常.

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

import {Component, Input, OnInit} from '@angular/core';从@angular/router-deprecated"导入 {Router, RouteParams};从 './content-node' 导入 {ContentNode};从../services/content.service"导入{ContentService};@成分({选择器:'内容树',指令:[ContentTreeComponent],模板:`<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></ol><div class="error" *ngIf="errorMessage">{{errorMessage}}</div>`})导出类 ContentTreeComponent 实现 OnInit {构造函数(私有_contentService:内容服务,私有_router:路由器,私有_routeParams:RouteParams) { }错误消息:字符串;@Input('startNodeId')私人 _startNodeId:数字;contentNodes: ContentNode[];ngOnInit() {让 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).订阅(contentNodes =>this.contentNodes = contentNodes,错误 =>this.errorMessage = <any>error);}}

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

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

非常感谢.

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

解决方案

在新的路由器 (>= RC.0 <=RC.2) 中

 import 'rxjs/add/operator/first';...构造函数(私有路由器:路由器,私有routeSerializer:RouterUrlSerializer,私有位置:位置){router.changes.first().subscribe(() => {让 urlTree = this.routeSerializer.parse(location.path());console.log('id', urlTree.children(urlTree.children(urlTree.root)[0])[0].segment);});}

另见 Angular 2 RC1: 从使用的初始 URL 获取参数

I have a dashboard application which consists of a treeview component (which lists various content nodes) and a dashboard-edit component which renders some editable content depending on which branch of the tree is selected.

e.g. The tree is like this:

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

You click 'Arsenal' in the tree and it renders some content for that team in an editable panel on the page.

The component which renders the sub-components is like this:

@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
    ]
})

The editable content is rendered in a router-outlet so that each editable piece of content has its own distinct URL e.g. example.com/content/edit/123 where 123 is the id of the Arsenal content, for example.

This all works fine.

However, what I want to do is be able to access the id route parameter in the content-tree component. Currently, I'm pretty sure the code I have in that component should work:

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
            );
    }
}

But the nodeId variable in the ngOnInit method is always returned as 0.

Questions: Is it only possible to access route params in a component rendered by a router-outlet? If so, then is the best method to deal with this to create a second (named, because there will now be 2) router-outlet? If not, then what am I doing wrong?

Many thanks.

EDIT:

A working (and very ugly ;)) Plnkr has now been generated to show the basics of the app: http://plnkr.co/edit/W3PVk3Ss5Wq59IbnLjaK?p=preview. See comments for what is supposed to happen...

解决方案

In the new router (>= RC.0 <=RC.2) this would be

  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);
    });
  }

See also Angular 2 RC1: Get parameters from the initial URL used

这篇关于Angular2 在路由器插座之外获取路由器参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆