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.