Angular Series #6: Services in Angular
Why we need service:
A service in angular is generally used when you need to reuse data or logic across multiple components. Using Service, we are ensuring one of the principles of software development ‘don’t repeat your code’.
Let’s take example were we defined product list array in typescript instead now we can add one service to fetch the product list object,
Product.service.ts
As you see below we defined one method in service to return products object where we hardcoded the project array but in real time you can write logic to fetch data from the databases.
import { Injectable } from ‘@angular/core’;import {Iproduct} from ‘./product’;@Injectable()export class ProductService{getProducts():Iproduct[]{return [{pid:’1',pname:’TestProduct1',pstatus:’Sold’},{pid:’2',pname:’TestProduct2',pstatus:’Unsold’},{pid:’3',pname:’TestProduct3',pstatus:’Sold’}];}}
Prod-details.component.ts
Here we imported the service which we defined then to use that it’s important to add in providers. If we are registering service in the provider’s section of the component, then it is accessible to the component itself and all its child components on the other side if we are registering it in module level then all components can access that service.
If you notice over here we are calling the service in constructor was constructor is not the right place to call service. Service call generally issued over HTTP to remote servers if the network connection is slow or if the webserver is busy processing another request our service call could take time to return the data. So the right place to a service call is ngOnInit. NgOnInit executes after the constructor and most commonly used for component initialization and making service calls.
import { Component, OnInit } from ‘@angular/core’;import {Iproduct} from ‘./product’;import {ProductService} from ‘./product.service’;@Component({selector: ‘app-prod-details’,templateUrl: ‘./prod-details.component.html’,styleUrls: [‘./prod-details.component.css’],providers:[ProductService]})export class ProdDetailsComponent implements OnInit {products:Iproduct[];selectedradioval:string=’Total’;//With Constructorconstructor(private _productService:ProductService) {this.products=this._productService.getProducts();}ngOnInit() {}//With ngOnInitconstructor(private _productService:ProductService) {}ngOnInit() {this.products=this._productService.getProducts();}gettotalproductcount():number{return this.products.length;}getsoldproductcount():number{return this.products.filter(p=>p.pstatus===’Sold’).length;}getunsoldproductcount():number{return this.products.filter(p=>p.pstatus===’Unsold’).length;}Onproductradiobuttonchnage(selectedval:string):void{this.selectedradioval=selectedval;}}
Prod-details.component.html
<app-prod-count[all]=”gettotalproductcount()”[sold]=”getsoldproductcount()”[unsold]=”getunsoldproductcount()”(countradiobuttonselectionchange)=”Onproductradiobuttonchnage($event)”></app-prod-count><table><thead><tr><th>Product ID</th><th>Product Name</th><th>Product Status</th></tr></thead><tbody><ng-container *ngFor=”let product of products;”><tr *ngIf=”selectedradioval==’Total’ || selectedradioval==product.pstatus “><! — <tr *ngFor=”let product of products;” *ngIf=”selectedradioval==’Total’ || selectedradioval==product.pstatus “> →<td>{{product.pid}}</td><td>{{product.pname}}</td><td>{{product.pstatus}}</td></tr></ng-container></tbody></table><br/>
Thank You, See you in the next article !!
You can reach out to me here,
LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar
Email: vaibhavbhapkar.medium@gmail.com