Angular ActivatedRoute data returns an empty object
Edit: the problem is that I was trying to access the ActivatedRoute from a Component which is outside the <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.
I found a workaround on GitHub (thanks manklu) that I used in order to accomplish what I needed:
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
).
I Don't know the version spoken, but as of Angular 6,this worked for me:
(Ofcourse thanks to shinDath)
routeData; ngOnInit() { //child route param doesnt go up to parent route params. this.router.events.subscribe((val) => { if (val instanceof ActivationEnd) { if(!$.isEmptyObject(val.snapshot.params)){ this.routeData = val.snapshot.params; } } }); }
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); } }); }