Manually-passed Angular route variable gets undefined in component

admin

Administrator
Staff member
In my Angular component, I'm trying to get a variable that I manually pass from the route. I followed this tutorial: <a href="https://hassantariqblog.wordpress.c...-retrieve-data-property-from-angular2-routes/" rel="nofollow noreferrer">https://hassantariqblog.wordpress.c...-retrieve-data-property-from-angular2-routes/</a>. First, in my routing file, I added a data property to my route object, in which I define what I want to pass:

Code:
{
    path: ':id/dashboard/:sectionIndex',
    component: CampaignDashboardComponent,
    data: {
        section: 'dashboard' // this is what I need to retrieve in the component
    }
},

Here is my component:

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

@Component({
    selector: 'campaign-menu',
    templateUrl: './campaignMenu.component.html',
})
export class CampaignMenu implements OnInit {

    public sectionKey: string;

    constructor(
        private router: Router,
    ) {}

    ngOnInit() {
        this.router.events
            .filter((event: any) =&gt; event instanceof NavigationEnd)
            .subscribe(() =&gt; {
                var root = this.router.routerState.snapshot.root;
                while (root) {
                    if (root.children &amp;&amp; root.children.length) {
                        root = root.children[0];
                    } else if (root.data &amp;&amp; root.data["section"]) {
                        this.sectionKey = root.data["section"];
                        alert(this.sectionKey);
                        return;
                    } else {
                        return;
                    }
                }
            });
    }
}

In order to make this work, I have to manually change the route in the address bar of my browser. If I simply reload the page, the
Code:
sectionKey
variable doesn't get defined. When I do manually change the route, the variable gets defined, and I see it in the alert. However, the variable immediately gets undefined again, which I prove by trying to display the variable in the template. Do you have any idea why might cause this variable to get undefined?