Angular JS - Using Services For Holding\Sharing Data

88 Views Asked by At

I'm working on some Angular JS SPA .

I'm trying to understand if from architecture perspective it is correct to use angular services for holding\sharing data between views or should I use some caching mechanism.

My need is to hold and share any REST response and fetch again by demand.

Unfortunately I couldn't get clear answer if services is the correct place for holding the data.

Please advice based on your experience.

Thanks.

2

There are 2 best solutions below

0
Akl On

Yes Service is best for holding your data or sharing data between controllers.

Thanks

3
Matt M On

AngularJS has a $cacheFactory service you can use to manage data. In the example I linked to, they create a 'service' using the $cacheFactory. I've done something similar in an app I've created where I made a 'caching service' that has methods that I expose to add/remove items from a $cacheFactory cache (data I retrieved over $http calls).

You didn't give a lot of detail to go on, but I would say that generally speaking, it's a good practice to use a service to hold the cached data.

EDIT

You can also look into using $resource, which has built in support for caching. Not sure what your app specifically requires, but if you feel you need to maintain the cache yourself, use a service. Having each service maintain it's own caching logic is more likely to be an issue later if something changes.