I have a route registered with some data:
const routes: Routes = [ {path: 'my-route', data: { title: 'MyTitle' }, component: MyComponent}, ];
and I'm trying to access to the route's data using ActivatedRoute
:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({...}) export class MyComponent implements OnInit { private routeData; constructor(private route: ActivatedRoute) {} ngOnInit() { this.routeData = this.route.data.subscribe((data) => { console.log(data); // this is returning an empty object {} }); } }
but for some reasons data
is an empty object.
How to solve this problem?
<router-outlet>
. So it looks like that this is the intended behaviour.However I still think that my answer below can be useful to anyone who is trying to accomplish the same thing.
import { Component, OnInit } from '@angular/core'; import { Router, RoutesRecognized } from '@angular/router'; @Component({...}) export class MyComponent implements OnInit { private routeData; constructor(private router: Router) { } ngOnInit() { this.router.events.subscribe((data) => { if (data instanceof RoutesRecognized) { this.routeData = data.state.root.firstChild.data; } }); } }
doing this way this.routeData
will hold the route data that I needed (in my case the page title
).
Get route custom data for component outside <router-outlet> (Angular 8):
constructor(private router: Router) {} ngOnInit() { this.router.events.subscribe(data => { if (data instanceof ActivationStart) { console.log(`Custom data`, data.snapshot.data); } }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With