Communication between two Components with Observable & Subject — Angular 2/6

This is a quick post to show an example of something that got me stuck for a little while — how to communicate between components in Angular 2/6.

Devam Soni
Mar 19 · 2 min read

The solution is to use an Observable and a Subject (which is a type of observable), I won’t go too much into the details about how observable work here, there are two methods that we’re interested in: Observable.subscribe() and Subject.next().

Observable.subscribe()

The observable subscribe method is used to subscribe to messages that are sent to an observable.

Subject.next()

The subject next method is used to send messages to an observable which are then sent to all subscribers of that observable.

see on StackBlitz ( https://stackblitz.com/edit/cart-badge)
File Structure of Project:

Angular 2/6 Product Service

The product service enables subscribing to number and sending number from any component in the application.

IMPORTANT: If you add a service like this to your application don’t forget to add it to the providers: [...] section of your app.module.ts file.

product.service.ts

Angular 2/6 Navigation Component that Receives number

The navigation component uses the product service to subscribe to new number and make them available to the navigation component template via the number property.

navigation.component.ts

Angular 2/6 Product Component that Send numbers

The product component uses the number service to send numbers to the app component.

product.component.ts

JavaScript in Plain English

Learn the web's most important programming language.

Devam Soni

Written by

UI Developer

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade