I have created a factory as a service to get some data from server using Web API call, but if i need to get same data again, I need to hit API again, I want to use same data in further places and don't want to make Web API call again.
Is there any way to persist data in angular js?
You can use HTML5 Web Storage for that.
if you're making an async call inside your service and the data you're fetching are "static" it makes sense to cache them to avoid a new overhead each time you need them. Cache is disabled by default.
Ways to sharing the data across the application :
1. Using service
We can create a service to
set
andget
the data between thecontrollers
and then inject that service in the controller function where we want to use it.Service :
Controllers :
Here, we can see that
myCtrl1
is used for setting the data andmyCtrl2
is used for getting the data. So, we can share the data from onecontroller
toanother controller
like this without making any further API call.2. Using Session storage
Create factory service that will save and return the saved session data based on the key.
controller :
Inject the
storageService
dependency in the controller toset
andget
the data from the session storage.