I am loading some backend api data on homepage in ngOnInit()
export class MyComponent{
homepagedata:any; // displayed on the html
ngOnInit() {
this.homepagedata=// calling service
}
}
This is my routes
{
path: 'home',
component: HomeComponent,
children: [
{
path: 'dashboard/:userid', //
component: DashboardComponent,
},
]
}
So when I navigate to dashboard ,and then navigate again to home ,my home component doesn't gets refreshed ,may be because ngOnInit()
is called once .How to call this ngOnit()
every time I navigate to home.I tried with ngAfterViewInit()
but its also only called once.
I found a similar problem here.But here it is navigating after the function call ,which is not in my case .There are many child components in my case ,and I am looking for one solution that can fit all.Thanks
@Input() and @Output() give a child component a way to communicate with its parent component. @Input() lets a parent component update data in the child component. Conversely, @Output() lets the child send data to a parent component.
In the parent component, declare the property that you want to receive in the child component, say 'ParentId'. While including the child component inside the parent component, bind the 'ParentId' property to the child component using property binding.
Perhaps you can have your parent component listen for route changes and update your data accordingly:
export class MyComponent {
homepageData: any;
constructor(private router: Router) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
// update this.homepageData
});
}
...
}
One solution could be to listen to the router event corresponding to the navigation to your home page and load data when it happens.
Here is a stackblitz demonstrating a possible implementation.
@Component({
template: `
<p>home page content (load count: {{loadCount}})</p>
<hr>
<p>child page:</p>
<router-outlet></router-outlet>
`,
})
export class HomeComponent
{
loadCount = 0;
constructor ( private router: Router )
{
// On router event...
this.router.events
// ...if event is a navigation end and if target is home page...
.pipe(filter(event =>
event instanceof NavigationEnd && event.urlAfterRedirects === '/home',
))
// ...load data.
.subscribe(() => this.load());
}
private load ()
{
// Simulate data loading by incrementing a counter.
console.log('load home data');
this.loadCount++;
}
}
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