How to get current route custom data in angular 2? How to get current route custom data in angular 2? angularjs angularjs

How to get current route custom data in angular 2?


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


For Angular 4+

If you place the following code in the parent or upper level components like AppComponent then it won't work. It only works on child or lower level components for which you've defined the route custom data:

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

So, if you want to access the route custom data globally from a parent or upper level component to access the change in the route custom data then you've to listen to router events particularly RoutesRecognized or NavigationEnd events. I'm gonna show two procedures with 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);       });    } }

Second Approach is using:

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: Even though last one is shorter and usually works, but, if you have nested routes then it is encouraged to use the first one.


After I tested various solution, the angular support group answer actually solved this problem nicely.

ActivatedRoute doesn't carry data, and here's the solution for detecting the page variable within the 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);      }    });  }}