How to get data from Route or ActivatedRoute when subscribing to router.events.subscribe in Angular2?

angular, angular-ui-router

Solution

Something like this:

constructor(private router: Router, 
        private activatedRoute: ActivatedRoute)
{

 this.router.events
        .filter(event => event instanceof NavigationEnd)
        .map(() => this.activatedRoute)
        .map(route => route.firstChild)
        .switchMap(route => route.data)
        .map(data => data['asdf'])
}

- For every events from router, I filter only NavigationEnd event

- Then I map this event to the activatedRoute (because I want to read the value of activatedRoute on NavigationEnd).

- I map the activatedRoute to the firstChild (first children declared with RouterModule.forRoot()).

- Then a switchMap is made to get the data of this route, a switchMap because data is an observable.

- Finally I map the data object to the key I want, in this case asdf

Problem

I'm trying to get the data from a Router whenever the Route changes but I'm not having success. Here I set the `asdf` property ``` @NgModule({ bootstrap: [AppComponent], declarations: [ AppComponent, LoginComponent, DashboardComponent, OverviewComponent, ], imports: [ BrowserModule, FormsModule, RouterModule.forRoot([ { path: '', pathMatch: 'full', redirectTo: '' }, { component: LoginComponent, path: 'login' }, { children: [ { path: '', pathMatch: 'full', redirectTo: 'overview', data: { asdf: 'hello' } }, { component: OverviewComponent, path: 'overview', data: { asdf: 'hello' } }, ], component: DashboardComponent, path: '', }, ]), ], }) export class AppModule { } ``` And here I can get the URL from the router when the route changes but `asdf` is undefined :( ``` import { Component, OnDestroy, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ActivatedRoute, NavigationEnd } from '@angular/router'; @Component({ selector: 'cs-map', styleUrls: ['map.component.css'], templateUrl: 'map.component.html', }) export class MapComponent implements OnInit { private routerSub; constructor(private router: Router, private activatedRoute: ActivatedRoute) { } public ngOnInit() { this.router.events.subscribe((val) => { if (val instanceof NavigationEnd) { let url = val.url; console.log(this.activatedRoute.snapshot.data['asdf']); // data is defined but asdf is not :( } }); } } ``` How can I get `asdf`'s value? Edit: I'm navigating to `/overview`

Original source

Related problems