At your service

So far, we’ve used services in our Angular 2 application to share data between components.  It’s one of the recommended ways of doing so by the official documentation (along with things like Input/Output and Event Emitter).  And so far, I think I like the ‘shared service’ option the best.  It encourages the use of Observables, which I’m coming to like more and more.

Side note- it seems like a lot of the use cases that surround Observables involve streams of data coming from a server (or database as a service, like Firebase).  But they can really be used for a whole lot more (mouse events, drag and drop, etc).  In some of our Angular 2 views, we will use an Observable (and corresponding subscription) to ensure data is updated between components on that same view.

Example: one screen has a set of charts (created in d3.js – future post about that awesome library as soon as I rise above the ‘bumbling moron’ level of proficiency) above a listing of activity types.  An admin can edit those activity types- when they do, it fires the .next method on an Observable the chart (same screen) subscribes to.  That way, the chart updates as edits are made below.  In a traditional request-response type website setup, this wouldn’t have been an issue, but this would also have required a full refresh from the server!

Anyway, the point of this post wasn’t supposed to be a commercial for RxJS (also- Observables are not just for Javascript- they have libraries for just about everyone!).  The point was regarding services in Angular 2.  Generally, when you want to share data between components, you’ll declare the service in your providers array at the module level.  If I’m understanding correctly, that will create one instance of the service (a singleton function, I think?) which enables the sharing capability.  However, sometimes this isn’t what you want.

Example: we created a PaginationService to provide some of the basics of creating ‘pages’ (viewing 10/25/50 items onscreen at a time and allowing scrolling around by links for more).  But when declared at a shared, module level, it doesn’t really work right.  In this case, each component should have its own instance of the service (you don’t want changing pages on one view to also change another- that gets very confusing very quickly).

So, after swearing at the screen for a few minutes, I realized the answer was simply to move the PaginationService out of the module’s providers array and into the individual component’s providers array.  Each component gets its own instance and it works like a charm!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s