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',
ponent: HomeComponent,
children: [
{
path: 'dashboard/:userid', //
ponent: DashboardComponent,
},
]
}
So when I navigate to dashboard ,and then navigate again to home ,my home ponent 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 ponents in my case ,and I am looking for one solution that can fit all.Thanks
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',
ponent: HomeComponent,
children: [
{
path: 'dashboard/:userid', //
ponent: DashboardComponent,
},
]
}
So when I navigate to dashboard ,and then navigate again to home ,my home ponent 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 ponents in my case ,and I am looking for one solution that can fit all.Thanks
Share Improve this question edited Oct 2, 2019 at 7:25 asked Oct 2, 2019 at 7:12 user10091301user100913012 Answers
Reset to default 6Perhaps you can have your parent ponent 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++;
}
}