Service-to-service injection lets one service use another service easily. It helps keep code organized and reusable.
Service-to-service injection in 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.
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' }; } }
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(); } }
CalculatorService uses MathService to calculate the square of a number. This shows how one service calls another.
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));
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.
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.
Practice
Solution
Step 1: Understand service-to-service injection concept
Service-to-service injection allows one service to use another service's methods or data by injecting it via the constructor.Step 2: Identify the purpose
This helps keep code clean and reusable by sharing logic between services without duplication.Final Answer:
To allow one service to use another service's functionality easily -> Option AQuick Check:
Service-to-service injection = sharing logic between services [OK]
- Thinking services create multiple instances by injection
- Confusing services with components for DOM manipulation
- Believing injection replaces components with services
LoggerService into another service's constructor?Solution
Step 1: Recall Angular constructor injection syntax
Angular uses TypeScript constructor parameters with access modifiers (like private) followed by the variable name and type.Step 2: Match correct syntax
The correct form isconstructor(private logger: LoggerService) {}. Other options have incorrect order or missing keywords.Final Answer:
constructor(private logger: LoggerService) {} -> Option CQuick Check:
Access modifier + variable name + type = correct injection [OK]
- Placing 'private' after the variable name
- Swapping variable name and type order
- Omitting access modifier like private or public
DataService.getData() return?import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class LoggerService {
log() { return 'Logged'; }
}
@Injectable({ providedIn: 'root' })
export class DataService {
constructor(private logger: LoggerService) {}
getData() {
return this.logger.log() + ' Data';
}
}Solution
Step 1: Understand service injection and method calls
DataService injects LoggerService and calls itslog()method, which returns 'Logged'.Step 2: Analyze getData() return value
getData() returns the string from logger.log() plus ' Data', so the result is 'Logged Data'.Final Answer:
'Logged Data' -> Option DQuick Check:
Injected method output + ' Data' = 'Logged Data' [OK]
- Assuming logger is undefined due to missing initialization
- Mixing order of concatenated strings
- Forgetting to call the log() method
@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private authService: AuthService) {}
}
// AuthService is not decorated with @InjectableSolution
Step 1: Check injection requirements
Angular requires any service to be decorated with@Injectableto be injectable into other services or components.Step 2: Identify missing decorator
AuthService lacks@Injectable, so Angular cannot inject it into UserService.Final Answer:
AuthService must be decorated with @Injectable to be injected -> Option BQuick Check:
@Injectable missing on injected service = error [OK]
- Thinking access modifier in constructor is wrong
- Believing services can't be provided in root
- Assuming services can't inject other services
ApiService and CacheService. You want ApiService to use CacheService to store data before returning it. Which is the best way to implement this service-to-service injection pattern?Solution
Step 1: Understand service responsibilities
ApiService handles API calls, CacheService handles data storage. ApiService should use CacheService to store data.Step 2: Apply service-to-service injection
Inject CacheService into ApiService's constructor, then call CacheService methods inside ApiService to store data before returning it.Step 3: Avoid bad patterns
Injecting ApiService into CacheService or duplicating methods breaks separation of concerns. Using global variables is bad practice.Final Answer:
Inject CacheService into ApiService constructor and call cache methods inside ApiService -> Option AQuick Check:
Inject dependent service into main service for clean logic [OK]
- Injecting main service into helper service causing circular dependency
- Duplicating logic instead of reusing services
- Using global variables instead of injection
Ready to prove it?
Pass the test and this pattern moves unknown
