0

trying to get the data from router in different component. but its showing {} value.

app-routing.module.ts

{
  path: '',
  loadChildren: './pages/pages.module#PagesModule',  
},

pages-routing.module.ts

path: 'namescan',
        component: NamescanComponent,
        data: { title: 'Name Title' }

header.component.ts

private routeData;
constructor(public router: Router, public activatedRoute: ActivatedRoute) {    
}

ngOnInit() {
    this.activatedRoute.data.subscribe(data => console.log(data.title));    
}

even find the smiliar question and even try to update the code but still not working Angular ActivatedRoute data returns an empty object

any idea, how to get the data value from router. TIA

2 Answers2

1

you can use activatedRoute.snapshot.data so it should look like

constructor(activatedRoute:ActivatedRoute) 

ngOnInit() {
    console.log(this.activatedRoute.snapshot.data);
  }
jitender
  • 10,238
  • 1
  • 18
  • 44
  • `{ }` empty object – Faisal Janjua Oct 09 '19 at 10:29
  • never use the snapshot, it removes the dynamic aspect of your router –  Oct 09 '19 at 10:29
  • @Maryannah I was thinking of same solution as of yours but I thought if data static and never going to change then `route.data.subscribe` will create a subscription that will need to unsubscribe later on else may result in memory leak – jitender Oct 09 '19 at 10:32
  • 1
    That's true about the memory leak ! I'm removing my downvote and upvoting instead, didn't think of that aspect for newcomers –  Oct 09 '19 at 10:38
  • (Sorry for the edit while I'm at it, my downvote was too old to be removed, had to edit your answer to change it) –  Oct 09 '19 at 10:42
0

Why not use the simple & efficient way ?

constructor(route: ActivatedRoute) {
  route.data.subscribe(data => console.log(data.title));
}
  • @FaisalJanjua then please provide a [mcve] reproducing it –  Oct 09 '19 at 10:29
  • @FaisalJanjua update it with a [mcve] (actually click on the link to se what it is) provided on, for instance, https://stackblitz.com –  Oct 09 '19 at 10:36
  • @FaisalJanjua here it is, working : https://stackblitz.com/edit/angular-9t8s3v?file=src%2Fapp%2Fapp.module.ts. Do the same to reproduce your issue. –  Oct 09 '19 at 10:41
  • Actually at my side its huge application, trying to get on the stackblitz.... quick question, I am using **app-routing.module.ts** `loadChildren: './pages/pages.module#PagesModule',` and all the routes are in other `routing` file. – Faisal Janjua Oct 09 '19 at 10:55
  • @FaisalJanjua that's why it's called **minimal**, because you only *reproduce* the issue, you don't actually put your whole code ... And again, provide the [mcve] and I'll tell you what's the issue, I gave you everything I could here ! –  Oct 09 '19 at 10:58