javascript - AngularJS - Store data within services? -
suppose have users service calls external api
in order avoid calling api twice (e.g. once parent page, , again child elements need it).
would ok store data within service?
e.g. myservice.username, myservice.userid, etc.
i've read it's bad practice store data in services; why i'm asking
note: not need data persist. should refresh upon page load.
i think caching data in service has several advantages, must aware however, happening.
here few facts , infos regarding services:
- they singletons, meaning there 1 instance in whole application
- a service there (you don't need create explicitly)
- a service can cache data can usefull, e.g. maintain state of view/page and/or reduce amount of requests sent server
- services can used exchange data between different components (e.g. directives, controllers, other services, etc.)
- services can injected ever need them
- services can tested without ui-related issues..
in cases might need pay attention tough:
- if different components share , modify same service, might "mess" each others data - can desired, might have side-effects
- services cache long application "lives", i.e. if user reloads or revisits page, data/state lost. if want persist data, can store service's data in local storage example.
i think service if has clear, understandable api , doesn't try much. , if can reused several compontents, seems case requirements.
please note of copied answer in different post regarding services vs. directive. maybe can find more info there.
Comments
Post a Comment