Angular2 Get router settings outside of the router

I have a toolbar application that consists of a treeview component (which lists the various content nodes) and a dashboard editing component that displays some editable content depending on which tree branch is selected.

eg. The tree is as follows:

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

You click Arsenal in the tree and it displays some content for this command in an editable panel on the page.

The component that displays the subcomponents is as follows:

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

Editable content is displayed in the router-outlet , so that each editable piece of content has its own separate URL, for example. example.com/content/edit/123 where 123 is the identifier of the content of the Arsenal, for example.

It all works great.

However, what I want to do is access the id route parameter in the content-tree component. Currently, I am sure that the code that I have in this 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 nodeId method always returns as 0 .

Questions: Is it possible to only access the route parameters in the component displayed by the router? If so, then the best way to handle this is to create a second (named because there will now be 2) router-exit? If not, what am I doing wrong?

Many thanks.

EDIT:

Worker (and very ugly;)) Now Plnkr was created to show the basics of the application: http://plnkr.co/edit/W3PVk3Ss5Wq59IbnLjaK?p=preview . See comments on what should happen ...

+9
angular typescript angular2-routing
source share
5 answers

In the new router ( > = RC.0 <= RC.2 ) this will 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 Source URL

+3
source share

Get active route from outside a component in angular 2.1.0 and Router 3.1.0

I found a good way to get all parameters, queryParmas, segments and fragments from the displayed route from anywhere in your application. Just add this code to any component where you need it, or create a service that can be entered into your application.

 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 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); } }); } ... 
+11
source share

Is it possible to only access the route parameters in the component displayed by the router?

Yes, <router-outlet></router-outlet> tells Angular2 to treat the containing component as a routing component. Therefore, you cannot get the RouteParams instance injected into the class because it was not created using the routing directive.

If not, what am I doing wrong?

I would not say that you are doing something wrong, you just had the wrong idea about how it was developed. I also have this initial fallacy. I found this Angular2 to be a great source for understanding how to transfer data and how to communicate between the parent and child components.


In your specific case, I suggest removing RouteParams from the constructor ContentTreeComponent , since it will only be available when rendering from the "routing" component.
 export class ContentTreeComponent implements OnInit { constructor( private _contentService: ContentService, private _router: Router ) { } // Omitted for brevity... } 

Then, to get the id , you probably have to share a little more of your top-level code so I can see where it comes from ...

+4
source share

Due to the solutions found in this post that could not solve my problem, I just added another solution that can currently fix or help you solve this problem in another post with a similar question: Angular 2: How to get route parameters outside the router output

0
source share

This solution worked for me: full 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; } 

Toxic loans.

0
source share

All Articles