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.

Important reasons for developers to adopt Angular JS development

 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...

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 has been a top choice for web development and it's the latest version AngularJS has gained popularity in the industry. This java script framework has created its prominent position in creating web apps.
Regardless of whether there are numerous different systems accessible for web development, AngularJS can support among them all. Since its introduction in the market, Angular has been creating waves in the market.

Introduction

Angular js is a powerful framework that was developed by Google. It is used to build dynamic apps with power-packed features. It was first introduced in 2010 and created by developers at Google. This framework was created to simplify and remove the challenges in creating dynamic apps. It uses HTML, CSS, and java script to create dynamic single-page applications. Angular Js is inclusive of Mongo DB and it is a frontend fragment of Mean Stack. In the developer's community, Angular is considered as a reliable and fast Java script framework. Many popular apps like PayPal. You tube, Netflix, the guardian, Lego are built using the AngularJS framework.

In this blog, we are listing some compelling reasons to pick angular development to familiarize you with its potential

• Open-source framework: It is not a library but open-source frameworks that enable the developers to build well-performing single page web applications. Just after its launch, it became hugely popular among the developers and it is not going to come at a halt.

• Simplified MVC structure: Developers use AngularJS to build robust and interactive web applications. AngularJS framework uses MVC architecture to create interactive applications. AngularJS makes it easy for developers to create apps as they are only required to split the applications.

• Extensive community: As angular is built by Google, it is backed by a very large community of professionals. The Angular JS conferences of the professionals are held all over the world. Hackathons are also organized in IT communities that include some professional and skilled engineers who can help with the queries and questions related to Angular.

• Declarative code system: In Angular JS developers can create declarative patterns by using declarative paradigms. It enables developers to be less heavy, and easy to read. In this framework, the developers get data models that are not too complex to write that abolishes the need to use any getter/setters and with easy data manipulation.

• Two-way data binding: It is one of the impeccable features that makes Angularjs popular in the developers' community. It allows seamless projections of the models and data binding. In this framework, any changes in the user interface make an impact on the application objects. The developers are not required to fresh the cycle and that makes it vulnerable to bugs.

• Using directives: AngularJS makes use of Directives as the developers can build custom HTML tags that function as custom widgets and it can be possible using directives. Its implications are also in the case of the use of decorating components and manipulation of DOM elements in appealing ways.

• Enterprise-level testing: When using Angular JS there is no need for demanding any other supplementary framework or additional plugins. In the process, parts of applications are put in the angular framework which is not too complex for manipulation. In module separation, developers can load essential services in an effective way for the performance of automatic testing.

• Client-side situation: AngularJS mainly works at the client-side and it is fully compatible with both web and mobile browsers. It can function with any projects without the need for any backend notifications. The developers can easily use AngularJS for the front end of applications.

• Easy to use: AngularJS is rich with its features and facilitates developers to reduce any need for writing codes. It reduces the burden of developers by the application of MVC architecture and data models.

Many other significant features make AngularJS prioritize by the developers than other Javascript frameworks. The above-mentioned reasons have made it the top choice for reputed companies all across the globe for web development. Developers at the company master the skills to work with Angular JS development for web. The company is equipped with dedicated professionals having sound technical knowledge of working with AngularJS. We offer offshore services to extend our reach all across the globe with various models. We have more than 15 years of experience in the industry that we use to deliver high-quality solutions by leveraging the latest technology and quality standards.

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]