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