Angular 8 Communication between Components using Subject and Observable

Angular 8 Communication between Components using Subject and Observable

Angular 8 Communication between Components using Subject and Observable - While working with angular, Very frequently we need to share data between components. There are various ways to share data between Angular components. These are..

Angular 8 Communication between Components using Subject and Observable - While working with angular, Very frequently we need to share data between components. There are various ways to share data between Angular components. These are..

  1. Using @Input()
  2. Using @Output()
  3. Using Services
  4. Parent component calling ViewChild
  5. Parent interacting with a child using a local variable
  6. Using Observable and Subject

Here I will use Observable and Subject to share data between components. I will try to explain the basic use of it to share data between the components. For detailed information you can visit the official site of angular.

Observable.subscribe()

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

Subject.next()

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

** Let's Get Started.**

Step 1: Create Angular App and Cart Service

create an Angular app with Angular CLI. and create a service named CartService and put below code inside that file:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class CartService {
private subject = new Subject();

addToCart(product:string) {
this.subject.next({name:product});
}

clearCart() {
this.subject.next();
}

getCart(): Observable{
return this.subject.asObservable();
}
}

Step 2: App Component which receives data from Product Component

Cart service is used in this component to subscribe to new product data and push them into the products array.

import { Component, OnDestroy,OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { CartService } from './cart.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})

export class AppComponent implements OnDestroy {
subscription: Subscription;
cart: any;
products: any[] = [];
constructor(private cartService: CartService) {
// subscribe to product component
this.subscription = this.cartService.getCart().subscribe(product => {
if (product) {
this.products.push(product);
} else {
// clear product
this.products = [];
}
});
}

ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}

}

Step 3: Product Component for sending product data

 import { Component} from '@angular/core';

import { CartService } from '../cart.service';

@Component({
selector: 'app-home',
templateUrl: './product.component.html'
})
export class ProductComponent{
constructor(private cartService: CartService) {}

addToCart(): void {
// send product data to subscribers via observable subject
this.cartService.addToCart('Product item from Product Component to App Component');
}

clearCart(): void {
// clear cart
this.cartService.clearCart();
}
}

Conclusion

In this demo, we understand the data sharing between angular components using Subject and Observable. You can find other demos at Angular sample application

That’s all for now. Thank you for reading and I hope this post will be very helpful for data sharing between angular 8 components using Subject and Observable.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Important reasons for developers to adopt Angular JS development

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular...

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.