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.
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().
The observable subscribe method is used to subscribe to messages that are sent to an observable.
The subject next method is used to send messages to an observable which are then sent to all subscribers of that observable.
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
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.
Angular 2/6 Product Component that Send numbers
The product component uses the number service to send numbers to the app component.