How to get current user route data in angular 2?

I set the routes as shown below

const appRoutes: Routes = [ { path: 'login', component: LoginComponent, data: { title: 'Login TTX' } }, { path: 'list', component: ListingComponent, data: { title: ' TTX Home Page', module:'list' } }, { path: '', redirectTo: '/login', pathMatch: 'full' }, ]; 

now when i come to the '/list' route and then 'listing.component.ts' i wrote below code

 export class ListingComponent { public constructor(private router:Router) { //here how i can get **data** of **list** routes } } 
+23
source share
9 answers
  public constructor(private route:ActivatedRoute, private router:Router) { console.log(route.snapshot.data['title']); } 
+18
source

For Angular 4+

If you put the following code in parent or top-level components like AppComponent then this will not work. It only works on child or lower-level components for which you have defined user route data:

  public constructor(private route:ActivatedRoute, private router:Router) { console.log(route.snapshot.data['title']); } 

So, if you want to access user-generated route data globally from a parent or top-level component, in order to gain access to change user-generated route data, you must listen to router events, especially the RoutesRecognized or NavigationEnd events. I am going to show two procedures with an AppComponent with two events:

First approach:

  export class AppComponent implements OnInit, AfterViewInit { constructor(private activatedRoute: ActivatedRoute, private router: Router) { } ngOnInit() { this.router .events .filter(event => event instanceof NavigationEnd) .map(() => { let child = this.activatedRoute.firstChild; while (child) { if (child.firstChild) { child = child.firstChild; } else if (child.snapshot.data && child.snapshot.data['custom_data']) { return child.snapshot.data['custom_data']; } else { return null; } } return null; }).subscribe( (customData: any) => { console.log(customData); }); } } 

The second approach uses:

 this.router.events .filter(event => event instanceof RoutesRecognized) .map( (event: RoutesRecognized) => { return event.state.root.firstChild.data['custom_data']; }) .subscribe(customData => { console.log(customData); }); 

Note. . Although the last one is shorter and usually works, but if you have nested routes, it is recommended to use the first one.

+21
source

After I tested the various solutions, the response of the corner support team actually solved this problem.

ActivatedRoute does not transfer data , and here is the solution for defining a page variable in data: { page: 'login' } .

 import { Router, RoutesRecognized } from '@angular/router'; export class AppComponent { page = ''; constructor(private router: Router) { // listen to page variable from router events router.events.subscribe(event => { if (event instanceof RoutesRecognized) { let route = event.state.root.firstChild; this.page = 'page-' + route.data.page || ''; console.log('Page', this.page); } }); } } 
+6
source

its work for a component that does not move (e.g. header):

 this.route.root.firstChild.snapshot.data['title'] 

and a complete example:

 import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router, NavigationEnd } from '@angular/router'; export class HeaderComponent implements OnInit { title: string; constructor(private route: ActivatedRoute, private router: Router ) { } ngOnInit() { this.router.events.subscribe(event => { if(event instanceof NavigationEnd) { this.title = this.route.root.firstChild.snapshot.data['title'] } }); } } 

Cerdit to this answer

+6
source

Asmmahmud's answer works before Angular 5.x, but 6.X breaks this.router.events since there are critical changes in rxjs 6.x. So just stumbled upon an update:

 import {filter} from 'rxjs/operators'; import {map, mergeMap} from 'rxjs/internal/operators'; router.events .pipe(filter(event => event instanceof NavigationEnd), map(() => { let route = activatedRoute.firstChild; let child = route; while (child) { if (child.firstChild) { child = child.firstChild; route = child; } else { child = null; } } return route; }), mergeMap(route => route.data) ) .subscribe(data => { console.log(data); }); 
+5
source

For those who are currently using Angular 6+ and the latest version of RXJS 6, here's what is based on the above ansers:

Routing Example:

 const routes: Routes = [ {path: 'home', component: HomeComponent, data: {title: 'Home'}}, // {path: '', redirectTo: 'home', pathMatch: 'full'}, {path: 'login', component: LoginComponent, data: {title: 'Login'}}, {path: 'dashboard', component: DashboardComponent, data: {title: 'Dashboard'}, canActivate: [AppAuthGuard]}, {path: 'eventDetails', component: EventCardComponent, data: {title: 'Details'}}, {path: '**', redirectTo: 'home', pathMatch: 'full'}, ]; 

How to get the title of an example:

 ngOnInit() { this.routerEventSubscription = this.router.events .pipe(filter(event => event instanceof RoutesRecognized)) .pipe(map((event: RoutesRecognized) => { return event.state.root.firstChild.data['title']; })).subscribe(title => { this.title = title; }); } 
+1
source

This worked for me in app.component.ts (ng 5)

  constructor( private router: Router, ) { router.events.subscribe((routerEvent: Event) => { this.checkRouterEvent(routerEvent); }); } checkRouterEvent(routerEvent: Event): void { if (routerEvent instanceof ActivationStart) { if (routerEvent.snapshot.data.custom_data) { this.currentpage = routerEvent.snapshot.data['custom_data']; console.log('4.' + this.currentpage); } } 
0
source

if you want to have current route data, you can get it from ActivatedRoute

 public constructor(private activatedRoute:ActivatedRoute) { console.log((activatedRoute.data as any).value); } 
0
source

You can subscribe to ActivatedRoute.data. This kind of sounds like a response from @ dinesh-kumar, but I suppose (activatedRoute.data as any).value activRoute.data (activatedRoute.data as any).value is a hack using the fact that activatedRoute.data implemented like a BehaviorSubject. But ActivatedRoute.data is set as Observable<Data> , so subscription is the right way (do not forget to unsubscribe, or take(1) , etc.) Or use the async channel, etc.

 constructor(private route: ActivatedRoute) { this.route.data.subscribe((data) => { console.log(data); }); } 
0
source

Source: https://habr.com/ru/post/1260511/


All Articles