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 angular.io 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!
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!