Cabe Skuriles Cabe Skuriles - 2 months ago 42
TypeScript Question

Angular 2 Activatedroute params not working in Service or outside <router-outlet>

I have a very strange problem:

<navigation-menu *ngIf="isLoggedIn"></navigation-menu>
<div class="content-wrapper" [ngClass]="{'fullContent' : !isLoggedIn}">
<section class="content">

The navigation-menu is a component for the nav menu.
In router-outlet content there is a component called "assets".

What I did in asset component:

import { ActivatedRoute}from "@angular/router";
constructor(private route: ActivatedRoute){}
public ngOnInit(): void {
this.route.params.subscribe(params => {
const id = params["id"];

This works and I get the parameters of my route (which is kind of "asset/:id).

Now I tried the same in my Navigation-Menu Component (which is "outside" the router outlet) and in a global service called contextservice.
Same code as above, but it is not even triggered on route change. If I try to get a current router snapshot

const strId = this.route.snapshot.params["id"];

after NavigationEnd event was triggered it is the same result: strId is undefined because params are an empty object.

It only works in my asset component.
Is this working as intended or how should this be handled?

My intension was to trigger an event from a global service (or a "global" component like the nav menu) which is listening to all route(-params) changes.

My only solution would be to parse the complete url after every NavigationEnd event which in my opinion is no proper way...Or to handle the params change in each child component (in router-outlet) itself.

Maybe I have just a basic error in understanding...


Solution from accepted answer: => {
if (val instanceof RoutesRecognized) {
var strId = val.state.root.firstChild.params["id"];

Don't forget to import RoutesRecognized from angular router!!


The component added by the router gets the router segment (ActivatedRoute) passed, but in a service there is no activated route. You can subscribe to and traverse the routes tree (router.firstChild...`) to get params out of a specific route sequement you need.