Blog>
Snippets

Using Angular Services for Reusable Business Logic

Demonstrate how to create an Angular service to encapsulate business logic for reuse across components.
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class BusinessLogicService {

  constructor() { }

  // Example business logic function
  calculateOrderTotal(orderItems: any[]): number {
    return orderItems.reduce((total, item) => total + (item.price * item.quantity), 0);
  }
}
This piece of code defines an Angular service called 'BusinessLogicService'. It includes an example business logic function 'calculateOrderTotal', which calculates the total price for a given array of order items. The service is injectable across the application by setting 'providedIn' to 'root'.
import { Component } from '@angular/core';
import { BusinessLogicService } from './business-logic.service';

@Component({
  selector: 'app-order-component',
  template: `Total Order Cost: {{ orderTotal }}`
})
export class OrderComponent {
  orderItems = [{ price: 10, quantity: 2 }, { price: 5, quantity: 4 }];
  orderTotal: number;

  constructor(private businessLogicService: BusinessLogicService) {
    this.orderTotal = this.businessLogicService.calculateOrderTotal(this.orderItems);
  }
}
This component 'OrderComponent' uses the 'BusinessLogicService' to calculate the total cost for an order. The 'orderTotal' is then displayed in the component's template. The service's 'calculateOrderTotal' method is called with the component's order items upon initialization, showcasing service reuse across the application.