0
0
Angularframework~5 mins

Service-to-service injection in Angular

Choose your learning style9 modes available
Introduction

Service-to-service injection lets one service use another service easily. It helps keep code organized and reusable.

When a service needs to get data from another service.
When you want to share logic between services without repeating code.
When a service depends on another service to perform its tasks.
When you want to keep your app modular and easy to maintain.
Syntax
Angular
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ServiceB {
  someMethod() {
    return 'result';
  }
}

@Injectable({ providedIn: 'root' })
export class ServiceA {
  constructor(private serviceB: ServiceB) {}

  useServiceB() {
    return this.serviceB.someMethod();
  }
}

Use private in the constructor to inject the other service.

Angular automatically creates and shares the service instance.

Examples
UserService uses LoggerService to log messages before returning user data.
Angular
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class LoggerService {
  log(message: string) {
    console.log('Log:', message);
  }
}

@Injectable({ providedIn: 'root' })
export class UserService {
  constructor(private logger: LoggerService) {}

  getUser() {
    this.logger.log('Getting user');
    return { name: 'Alice' };
  }
}
DataService calls ApiService to get data, showing simple service-to-service use.
Angular
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ApiService {
  fetchData() {
    return 'Data from API';
  }
}

@Injectable({ providedIn: 'root' })
export class DataService {
  constructor(private api: ApiService) {}

  getData() {
    return this.api.fetchData();
  }
}
Sample Program

CalculatorService uses MathService to calculate the square of a number. This shows how one service calls another.

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

@Injectable({ providedIn: 'root' })
export class MathService {
  square(num: number): number {
    return num * num;
  }
}

@Injectable({ providedIn: 'root' })
export class CalculatorService {
  constructor(private mathService: MathService) {}

  calculateSquare(num: number): number {
    return this.mathService.square(num);
  }
}

// Usage example (e.g., in a component or test):
const mathService = new MathService();
const calculatorService = new CalculatorService(mathService);
console.log(calculatorService.calculateSquare(5));
OutputSuccess
Important Notes

Always add @Injectable({ providedIn: 'root' }) to make services available app-wide.

Angular creates one instance of each service by default (singleton), so injected services share state.

Be careful to avoid circular dependencies where two services inject each other.

Summary

Service-to-service injection lets services use each other easily.

It keeps code clean and reusable by sharing logic between services.

Use Angular's @Injectable and constructor injection to connect services.