1

I am trying to setup a navigation bar that can display the title of the page. To do this, I wanted to have each route carry a param 'navTitle' in it's data.

In my route module, I pass the navTitle into the child route health.

const routes: Routes = [
  {
    path: 'health',
    loadChildren: () => import('./modules/health/health.module').then( m => m.HealthModule ),
    data: {navTitle: 'Health'}
  },
  {path: '**', pathMatch: 'full', redirectTo: '/health'}
];

However, on route /health, the data variable is still blank.

I loaded the navTitle by subscribing to the ActivatedRoute and keeping a reference to the navTitle because I want it to be able to change on navigation else where.

// get the page name
    this.pageNameSub = this.route.data.subscribe(
      data => {
        this.pageName = data.navTitle;
        console.log(data)
      },
      err => this.pageName = 'App'
    )

The log statement is showing the data is {} although I expected it to be {navTitle: 'Health'}.

I tried adding the data to the child router as well but it still did not populate.

My main question is, how do I pass initial data to Angular routes?

Rambou
  • 968
  • 9
  • 22
mep
  • 431
  • 1
  • 4
  • 15
  • Everything seems to be fine with your setup. Where does subscription of `route.data` take place (OnInit, constructor etc.)? Could you create a JSfiddle example in order to better understand the problem and probably help you with? :) – Rambou Sep 18 '19 at 23:10
  • 1
    The subscription takes place OnInit in my NavbarModule. I will get a JSfiddle for you asap – mep Sep 18 '19 at 23:36
  • Please take a look here https://stackoverflow.com/questions/36835123/how-do-i-pass-data-to-angular-routed-components – Rambou Sep 18 '19 at 23:55

1 Answers1

0

My initial understanding was that data was a global variable that could be accessed from any component. It seems that it can only be accessed from the route it was declared in. I added a log statement to HealthComponent and was able to log the data.

Therefore, I either need to include the navbar in the same route or create a service to allow for the page title to be set.

mep
  • 431
  • 1
  • 4
  • 15