Angular : Services and Dependency Injection


Angular is built on a modular and scalable architecture, and at its core are services and Dependency Injection (DI). These features enable clear separation of concerns, code reusability, and efficient dependency management. In this blog, we'll cover:

  1. Introduction to services
  2. How to create a service
  3. Dependency Injection in Angular
  4. Providers and injectors

1. Introduction to Services

A service in Angular is a class that encapsulates reusable logic or functionality that can be shared across multiple components in the application. For instance, services can:

  • Fetch data from APIs
  • Manage user sessions
  • Perform complex calculations
  • Share data between components

By moving business logic out of components and into services, Angular promotes the Separation of Concerns principle. This makes components lighter and easier to test while keeping the application maintainable.

2. How to Create a Service

Creating a service in Angular is straightforward. Here’s how:

Step 1: Generate a service

You can create a service manually or use the Angular CLI for convenience:

ng generate service my-service

This command generates two files:

  • my-service.service.ts - The service logic.
  • my-service.service.spec.ts - The unit test file for the service.

Step 2: Implement logic in the service

The service file will look like this initially:


import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root', // Registers the service at the root level
})
export class MyService {
  constructor() {}

  getMessage(): string {
    return 'Hello from MyService!';
  }
}
            

- The @Injectable decorator marks the class as a service that can be injected.
- The providedIn: 'root' option makes the service available globally.

Step 3: Use the service in a component

To use the service, inject it into a component via the constructor:


import { Component } from '@angular/core';
import { MyService } from './my-service.service';

@Component({
  selector: 'app-root',
  template: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
  message: string;

  constructor(private myService: MyService) {
    this.message = this.myService.getMessage();
  }
}
            


3. Dependency Injection (DI) in Angular

Dependency Injection (DI) is a design pattern used to manage dependencies in an application. In Angular, DI allows you to inject services, making them accessible where needed.

How DI works in Angular:

  1. Services are registered as providers.
  2. Angular's injector resolves dependencies by creating or providing an instance of the service.
  3. The dependency is injected into components, directives, or other services via their constructors.

For example:

constructor(private myService: MyService) {}

Here, Angular automatically injects an instance of MyService into the component's constructor.

4. Providers and Injectors

Providers

A provider tells Angular how to create an instance of a service. You can register a provider in different scopes:

  • Root scope (providedIn: 'root'): The service is a singleton and available throughout the app.
  • Feature module: Register the provider in a specific module.
  • Component scope: Register the provider in a specific component, creating a new instance for each component.

Example of registering a service in a module:


@NgModule({
  providers: [MyService],
})
export class AppModule {}
            

Injectors

Angular uses an injector tree to manage service instances:

  • The root injector provides services globally.
  • Child injectors can override or create specific instances for components or modules.

This hierarchical structure ensures efficient memory use and flexibility.

Conclusion

Services and Dependency Injection are essential concepts in Angular for building scalable, maintainable, and testable applications. By encapsulating reusable logic in services and leveraging Angular's DI system, developers can create robust and modular applications. Understanding providers, injectors, and service scopes is key to mastering this pattern.

Post a Comment

0 Comments