Q:

Manually-passed Angular route variable gets undefined in component

In my Angular component, I'm trying to get a variable that I manually pass from the route. I followed this tutorial: https://hassantariqblog.wordpress.com/2017/02/26/angular2-retrieve-data-property-from-angular2-routes/. First, in my routing file, I added a data property to my route object, in which I define what I want to pass:
{
    path: ':id/dashboard/:sectionIndex',
    component: CampaignDashboardComponent,
    data: {
        section: 'dashboard' // this is what I need to retrieve in the component
    }
},

Here is my component:
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) => event instanceof NavigationEnd)
            .subscribe(() => {
                var root = this.router.routerState.snapshot.root;
                while (root) {
                    if (root.children && root.children.length) {
                        root = root.children[0];
                    } else if (root.data && 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 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?

A:

I believe the issue is how you're attempting to access  the Route data in your controller. Instead of using Router, you should be using ActivatedRoute and then you have your choice of either subscribing to .data (if you need to react to changes after route load), or just accessing it directly via .snapshot.data.data_property. E.g.:
First, inject ActivatedRoute into your Controller:
constructor(
    private route: ActivatedRoute,
    ...
)

Then, the 2 ways you can access it:
Snapshot
let dataVal = this.route.snapshot.data.data_property;

Subscribe to Route Data
this.route.data.subscribe((data: any) => {
    let dataVal = data.data_property;
});

