Services and Dependency Injection

Services and Dependency Injection

Angular services and dependency injection are essential concepts in Angular development. Services provide a way to share data, logic, and functionality between different components, while dependency injection ensures that components receive their required dependencies seamlessly.

Services are classes that encapsulate reusable functionality, data, or logic that can be shared by multiple components. The services facilitate the separation of concerns, encourage code reuse, and provide a central place to manage and manipulate data. They play a key role in scenarios where you need to exchange data between components, make HTTP requests, manage business logic, manage state, interact with external APIs, or wrap reusable functions.

You can create a service manually or using the below command.

ng generate service <service-name>

Below is an example of a service

import { Injectable } from '@angular/core';
import { Example } from './example'; 
import { data } from './mock-data'; 

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

  constructor() { }
  private orders: Order[] = [
    new Order(
      1,
      'Dosa'
    ),
    new Order(
      2,
      'Idli'
    ),
  ];

  getOrders(): Order[] { 
    return this.orders; 
  } 
}

Note: To make the service available for dependency injection, you need to provide it at the appropriate level in your application. This can be done by adding the service to the providers array of a module or component metadata or as shown above.

To fetch the orders data in the component we can invoke the getOrders() method of the service by injecting it into the component as shown below.

export class OrdersComponent implements OnInit {   

  orders : Order[];

  constructor(private ordersService : OrdersService){ } 
  ngOnInit() { 
    this.getOrders(); 
  } 

  getOrders(): void { 
    this.ordersService.getOrders() 
        .subscribe(data => this.orders = data); 
  } 
}

Best practices:

  • Ensure services have a single responsibility and encapsulate a specific feature or functionality. This promotes maintainability, testability and reusability.

  • Leverage the hierarchical dependency injection system to organize services based on their scope and the components they require. This helps manage service instances and maintain the separation of concerns.

  • When providing services, consider the lifecycle and scope of your services. Place services at the module level if they are to be shared across components, or at the component level if they are specific to that component and its child components.

Did you find this article valuable?

Support Sankarshan Ramesh by becoming a sponsor. Any amount is appreciated!