Share data between angular components using service

Share data between angular components using service

Share data between angular components using service - This approach is ideal when you want to share data changes that occur on things like button clicks, form entires, and other user events...

Today I am going to show you the data sharing between angular components using services. As I have already shared demo on data sharing using input decorator and data sharing using output decorator. So if you want you can navigate to these sections to see the demo.

In the demo, I will take an example of cart system in any e-commerce site. In any e-commerce site there is a cart which user manipulates as per his preference to buy the items from the site. And if you see the value in cart show on every navigated page same, Means data is sharing there thought the multiple components.

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';

@Injectable()
export class CartService {

constructor() { }

public count = 0;
addToCart() {
this.count = this.count+1;
return this.count;
}

clearCart() {
return this.count = 0;
}

getCart(){
return this.count;
}
}

In the above service file, have created a public variable named count and 3 different methods to update the variable.

Step 2: Create component for product listing

open ts file of the product component and put below code

import { Component, OnDestroy,OnInit } from '@angular/core';

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

@Component({
selector: 'app-home',
templateUrl: './product.component.html'
})
export class ProductComponent implements OnInit {
cart: any;
public fileUrl;
constructor(private cartService: CartService) {}

ngOnInit(){
this.getCart();

}
getCart(): void {
this.cart = this.cartService.getCart();
}

addToCart(): void {
this.cart = this.cartService.addToCart();
}

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

}

In the above file, we have imported service and have methods to update the value in cart service.

now update product.component.html

<div class="text-center">
<a routerLink="">Product</a>&nbsp;|&nbsp;
<a routerLink="cart-detail">cart detail</a>
<p>Cart count</p><span *ngIf="cart && cart.text">{{cart.text}}</span>
<!-- main app container -->
<h2>This is produst listing page...</h2>
<p>Cart count:{{cart}}</p>
<button (click)="addToCart()" class="btn btn-primary">Add Product in cart</button>
<button (click)="emptyCart()" class="btn btn-secondary">Empty Cart</button>

</div>

In the above file we have shown the cart value and below we have two button to increase the cart value and make it empty.

Step 3: Create a Cart detail component

After creating a new component from the command line open the cart-detail.component.ts and put the below code:

import { Component, OnDestroy,OnInit } from '@angular/core';

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

@Component({
selector: 'app-home',
templateUrl: './product.component.html'
})
export class ProductComponent implements OnInit {
cart: any;
public fileUrl;
constructor(private cartService: CartService) {}

ngOnInit(){
this.getCart();

}
getCart(): void {
this.cart = this.cartService.getCart();
}

addToCart(): void {
this.cart = this.cartService.addToCart();
}

emptyCart(): void {
this.cartService.clearCart();
}

}

Same like product ts file we have called service methods from cart detail component also. Now update HTML file of cart detail component.

<div class="text-center">
<a routerLink="">Product</a>&nbsp;|&nbsp;
<a routerLink="cart-detail">cart detail</a>
<p>Cart count</p><span *ngIf="cart && cart.text">{{cart.text}}</span>
<!-- main app container -->
<h2>This is produst listing page...</h2>
<p>Cart count:{{cart}}</p>
<button (click)="addToCart()" class="btn btn-primary">Add Product in cart</button>
<button (click)="emptyCart()" class="btn btn-secondary">Empty Cart</button>


</div>

Now our component and service part is done.

Step 4: Update routing file

Make sure you have below routings in route file:

const routes: Routes = [{
path: '', component: ProductComponent
},
{
path:'cart-detail',component:CartDetailComponent
}
];

Also update app.component.html file inside app folder and remove all other code except .

Step 5: Run the app

After completing all the needed task now run the app with NPM start and check the app over the browser. You would see like below:

Conclusion

In this demo, we learn about the data sharing between angular components using services. You can find other demos at Angular sample projects

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

angular

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

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

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular. Angular is a Typesc

Visualizing data with NGX-Charts in Angular

Data Science, Data Analytics, Big Data, these are the buzz words of today's world. A huge amount of data is being generated and analyzed every day. So communica

Angular Workspace: No Application for You!

The how and why of using the --create-application flag with Angular CLI to create a Workspace without the initial application A nice addition to Angular CLI 7.0.0 was the --create-application flag. In this article I will discuss how and when to use this new feature. It will be especially useful when creating Angular libraries. NOTE: Angular CLI accepts both camelCase and kebab-case for this option. So, anywhere you see --create-application, you can also use --createApplication. For more detail

How to Build an Angular Application with Angular CLI

How to set up the Angular CLI and generate a Trivial App

Angular Platforms in depth. Part 1. What are Angular Platforms?

The Angular framework was designed to be a platform independent. That approach allows Angular applications to be executed across different environments — browser, server, web-worker, and even mobile devices. In this series of articles, I’m going to reveal to you how does it even possible — execute Angular applications across different environments. Also, we’ll learn how to build custom Angular platform which renders applications inside the system’s terminal using ASCII graphics. Articles: *