(I think I know the answer, but want to lay out my thought process and see if it is correct:)
Is it better for a provider/service to a) “provide” the data or b) contain the data?
Let me elaborate:
- In a) the provider starts with an empty
- Only when some code calls a
getData()it goes to the data source, Ionic Storage in this example, to get the data and sets it into the
dataobject and returns the data to the caller.
- The calling page then also creates a copy of
datain its own property to use in the templates.
- In b) the provider already gets the data from Storage when he is constructed and puts it into his
- Now all the pages using this Service can just call
.dataon the service instance to access this data.
- If the service instance is public, also the templates can use this variable directly (for e.g. looping over it).
- There is no copy of
datain the pages that has to be kept current, the data only exists in one place (the service, besides the Storage of course).
Having written this down I see that their are actually multiple differences between a) and b): a) starts with empty data in the provider, only to be filled when called. It also creates a copy of the data in the page. b) constructs the service to get the data by itself. The page doesn’t keep a copy and it is nicely encapsulated in the provider.
Is all this thinking correct?
Did I miss anything?
(Alternative c) would probably use Observables and be even better - but I am not experienced enough with that and first want to make the jump from a) to b) right now before thinking about Observables later.)