Services best practises


#1

Hi, i have a simple question about Services. If i got for example UserPage,where i want to display list of Users. So i Inject UserService(which gets data from db and saves it into UserList property) into UserPage constructor. Now there are two options how to access data from UserService. First one is to simply directly access UserList property on UserService. Second one is to create getter in UserService, and use it in UserPage. Which one is better practice?


#2

It depends on subtleties of how you want to be fetching the data, but in general I would say directly accessing a concrete data property in the service is virtually always not the best idea, because of concerns over when it is populated. Here is a different idea that involves exposing a Promise as a service property. If you want to eliminate all caching, your idea of a getter function is the best approach.


#3

That post you linked is fantastic, thank you. In case you’re interested: implementing Angular Redux, I’m mainly exposing BehaviorSubject.take(1) as Observables to pages, so very similar to your Promises idea, though Promises might have less overhead, I’ll have to look into that. But here’s my first hit: the BehaviorSubject snapshot is better for a service that’s listening to a database that might update in real time, like a mailbox inbuffer, while your Promise approach is probably more streamlined for calls that are guaranteed to take place at most once per execution. I need to look into this more, but I haven’t built the local cache manager yet, and I might lean on your code when I do, thanks.

One thank you I can give (in the unlikely event you don’t already know this) is that there’s a trick in ES6 to sidestep a lot of the check-for-falsy-bla-bla you complained about in that post. Like so:

const defaultItem = somethingNotAnnoying;

namedFunction(item = defaultItem) {}

I’ve used that quite a bit, and it’s made my code more streamlined.


#4

I tend to use ReplaySubject for situations where there is no sensible starting value.

Totally concur, and that’s pretty much the litmus test that I use for whether to use Promises or Observables: if it is only going to resolve once, use a Promise. If it may resolve multiple times, use an Observable.