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.

Mobile App Development Company India | Ecommerce Web Development Company India

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.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Web Development Services

Web Development Services

As one of the best Web Application Development Company, it provides a fine quality mobile app development service at an affordable price. Especially, it encourage start-ups that have unique ideas, by offering a more competitive price

HireFullStackDeveloperIndia is rated as one of the top Web Application Development Company in India by various industry magazines and review sites. They have a right blend of award-winning designers, expert programmers and Google certified digital marketers which make them a unique one-stop solution for hundreds of our clients, spread across all countries.

A Good website reflects not only your business but also it is one of the main factors why a potential customer would convert into Client. A good website design helps increase traffic driving leads to grow business. The best web design company create a custom design for each corporate website so as to help them meet their business goals.

Get Quote: https://hirefullstackdeveloperindia.com/get-a-quote/