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:
Here is my component:
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
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?
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) => 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
Code:
sectionKey