Skip to content Skip to sidebar Skip to footer

How To Get Route Data Into App Component In Angular 2

I have defined some route data in my app routing module like below: const appRoutes:Routes = [ {path: '', component: LoginComponent, data:[{PageName:'Login Page'}]}] I want

Solution 1:

Try to filter and loop your events instead of subscribe

constructor(router:Router, route:ActivatedRoute) {
    router.events
      .filter(e => e instanceofNavigationEnd)
      .forEach(e => {
        this.title = route.root.firstChild.snapshot.data['PageName'];
    });
}

Please check the following working demo: https://plnkr.co/edit/rBToHRaukDlrSKcLGavh?p=info

Solution 2:

If you had statically routed using Router object like below:

{
  path: '',
  pathMatch: 'full',
  component: NameComponent,
  data: { variableName: 'variableValue' }
},

On ngOnInit() you can use ActivatedRoute object to recover the data you passed from Router definition:

ngOnInit() {
  this.localVariable = this.route.snapshot.data['variableName'];
}

Obs: I am using Angular 5!

Solution 3:

This code was written by Todd Motto (Google Developer Expert) to access route data in a parent component or app component. Works like a gem.

import { ActivatedRoute, NavigationEnd, Router } from'@angular/router'import { filter, map, mergeMap } from'rxjs/operators'constructor(private route: ActivatedRoute, private router: Router) {}

ngOnInit() {
  this.router.events.pipe(
    filter(event => event instanceofNavigationEnd),
    map(() =>this.route),
    map(route => {
      while (route.firstChild) route = route.firstChildreturn route
    }),
    filter(route => route.outlet === 'primary'),
    mergeMap(route => route.data)
  ).subscribe(data =>console.log('data', data)
  )
}

See: https://ultimatecourses.com/blog/dynamic-page-titles-angular-2-router-events

In his example he is using route data to set the page title in app component.

Why accessing route data in a parent is so complicated I'll never know!

Solution 4:

For Angular 5+

This service retrieves data on the current route: (in my case "title")

import { Injectable } from "@angular/core";
import { Router, ActivatedRouteSnapshot } from "@angular/router";

@Injectable()
export classAppRoutingService{

  constructor(private router: Router) { }

  public getRouteTitle(): string {
    returnthis.getRouteData("title");
  }

  private getRouteData(data: string): any {
    const root = this.router.routerState.snapshot.root;
    returnthis.lastChild(root).data[0][data];
  }

  private lastChild(route: ActivatedRouteSnapshot): ActivatedRouteSnapshot {
    if (route.firstChild) {
      returnthis.lastChild(route.firstChild);
    } else {
      return route;
    }
  }
}

Component Logic:

import { Component, OnInit, OnDestroy } from"@angular/core";
import { Router, NavigationEnd } from"@angular/router";

// SERVICESimport { AppRoutingService } from"../../shared/services/app-routing.service";

@Component()
exportclassNavSubmenuComponentimplementsOnInit, OnDestroy {
  title: string = "";
  routerEvents: any;

  constructor(private router: Router, private appRoutingService: AppRoutingService ) { }

  ngOnInit() {
    this.title = this.appRoutingService.getRouteTitle();

    this.routerEvents = this.router.events
      .filter(event => event instanceofNavigationEnd)
      .subscribe(() => {
        this.title = this.appRoutingService.getRouteTitle();
      });
  }

  ngOnDestroy() {
    this.routerEvents.unsubscribe();
  }
}

Solution 5:

In my case this work for angular 8:

onActivate(outlet) in <router-outlet> will be called automatically every time when the route is activated.

in html

<router-outlet (activate)='onActivate(outlet)' #outlet="outlet"></router-outlet>

in component

onActivate(outlet: RouterOutlet) {
    outlet.activatedRoute.data.pipe(map(data =>console.log('Router data', data))).toPromise().then();
  }

Dont forget import

import {RouterOutlet} from'@angular/router';
import {map} from'rxjs/operators';

Post a Comment for "How To Get Route Data Into App Component In Angular 2"