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

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -