Reputation: 17118
I have the following code:
https://stackblitz.com/github/NickHodges/datademo
I am trying to display the data for a route on the page.
As you can see from the code, I have declared the path info like so:
const routes: Routes = [
{
path: 'comp1',
component: Comp1Component,
data: { info: 'Data from Comp1' }
},
{
path: 'comp2',
component: Comp2Component,
data: { info: 'Data from Comp2' }
}
];
I have declared a component like this:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styles: []
})
export class Comp1Component implements OnInit {
constructor(public route: ActivatedRoute) {}
ngOnInit() {}
}
and I am trying to access the data
property like so:
<p>
comp1 works!
</p>
<p>Comp1Data: {{ route.data['info'] }}</p>
So I go to the /comp1
route, but the data is not displayed.
How can I display the data
property on a Route
?
Upvotes: 5
Views: 6776
Reputation: 34022
I need to do this in my app.component
so it's always listening for route and data changes.
private readonly destroyRef = inject(DestroyRef);
private readonly router = inject(Router);
ngOnInit(): void {
this.router.events
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((event) => {
if (event instanceof NavigationEnd) {
const routeData = this.router.routerState.root.firstChild?.snapshot.data;
if (routeData) {
console.log(routeData);
//You will have to cast `routeData['foo']` to whatever types you are using here since it will not be know by the type system
}
}
}
}
Note that I am using inject()
instead of constructor
parameters, but it's the same thing.
Also note that the takeUntilDestroyed(this.destroyRef)
may not be needed but I figure it's good practice.
Upvotes: 1
Reputation: 5813
The data attribute on an ActivatedRoute
is an Observable
and you need to subscribe to it.
export class Comp1Component implements OnInit {
public data;
constructor(public route: ActivatedRoute) {}
ngOnInit() {
this.route.data.subscribe(data => this.data = data);
}
}
<p *ngIf="data">Comp1Data: {{ data.info }}</p>
Upvotes: 6