HomeComponent
ngOnInit()
{
console.log('loaded');
this.retrieveData();
}
retrieveData()
{
// this.dataService.getData().subscribe(...);
}
I am retrieving data when the component loads. When the user clicks on another routerLink
, for example, SettingsComponent
and returns back to the HomeComponent
, the function of course, is called again because the component has loaded again. But Everytime I return back to the component, it makes the function call again which creates too many unwanted HTTP requests. I need to prevent this and make sure the function is called only the first time. How do I do this? Should I use some other component lifecycle hook?
Okay I see you are using a service to load the data which is a good way.
Then you can simply cache the data somewhere and when you come back to a component check the cache for this data. I think you can store the data directly in your service which will keep it in the memory or you can put it in the localStorage
So first option would look like:
data.service.ts
then inside HomeComponent
IMPORTANT: if using this approach you should make your service global when declaring it in app.module.ts -> providers
and then not doing this:
=============================================
The localStorage approach
HomeComponenet
Both approaches has the limitation that you can't work with huge amounts of data, of course if you don't want to blow the browsers of users that are using your app :)