angular - How to get data from Route or ActivatedRoute when subscribing to router.events.subscribe in Angular2? -
i'm trying data router whenever route changes i'm not having success. here set 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 can url router when route changes asdf
undefined :(
import { component, ondestroy, oninit } '@angular/core'; import { router } '@angular/router'; import { activatedroute, navigationend } '@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 defined asdf not :( } }); } }
how can asdf
's value?
edit: i'm navigating /overview
data in routes must array of objects rather object define them
{ component: logincomponent, path: 'login', data:[{mykey1: myvalue1}] },
now retrieve use code in components constructor
constructor(private router:router, private activeroute:activatedroute) { router.events .filter(event => event instanceof navigationend) .map(_ => this.router.routerstate.root) .map(route => { while (route.firstchild) route = route.firstchild; return route; }) .flatmap(route => route.data) .subscribe(data => { console.log(data[0].mykey1); }); }
Comments
Post a Comment