When it comes to building web applications, developers inevitably must ask themselves a few questions: How is data going to be shared throughout this app? How should we notify components across this entire app when data updates or a RESTful API call returns?
This tutorial will show how to solve the problems posed by these questions in Angular 4 using Subscriptions, Observables from the ReactiveX (RxJS) library, and EventEmitters from the Angular Core library. This tutorial is written for those with some Angular experience and does not elaborate on the essentials of the framework. I recommend checking out the official documentation first if you’re unfamiliar with the Angular framework.
To demonstrate, I’ve created a simple application for a craft beer store with an inventory component and a store component. The beer store subscribes to any changes made to the beer inventory, and the beer inventory subscribes to purchases made in the beer store. A flowchart is included below to help illustrate the process and application design.
Simply put, whenever our inventory updates, either from the store component or the inventory component, we want to alert the rest of the app of the change using Subscriptions and EventEmitters.
step 1: start with the beer
Let’s start with a sample beer interface, which we will name “IBeer” (the convention is to prepend the letter “I” to interfaces in TypeScript).
step 2: establish a source of truth
Create a service to manage the source of your application’s data. This will be instrumental to sharing data between your beer inventory and beer store components.
step 3: create the inventory service, component, and view
The inventory service makes mock RESTful API calls to perform CRUD operations on the beer inventory. The service should have a method to get all beers currently in the inventory using an Observable, along with methods to create, update, and remove beers from the inventory. See inventory.service.ts for details.
The beer inventory component manages user interaction with the inventory and subscribes to any changes made to the beer inventory:
step 4: create the store service, component, and view
The store service makes mock RESTful API calls to purchase beer from the store:
After the service purchases the beer using APIs, the component manages user interaction with the store:
This concludes the walkthrough of the core application functionality. Using Subscriptions, Observables, and EventEmitters in tandem with a centralized service to manage our application’s data, we are able to share data between components in our Angular application. Be sure to check out the live demo and GitHub repository. I hope this was helpful to you!
If you have more questions, please reach out to us at firstname.lastname@example.org.