Performance: Service-to-service injection
This affects the initial load time and runtime responsiveness by controlling how services are created and shared in Angular apps.
import { Injectable, inject } from '@angular/core'; import { HeavyService } from './heavy.service'; @Injectable({ providedIn: 'root' }) export class UserService { private heavyService = inject(HeavyService); getUser() { return this.heavyService.fetchData(); } }
import { Injectable } from '@angular/core'; import { HeavyService } from './heavy.service'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private heavyService: HeavyService) {} getUser() { return this.heavyService.fetchData(); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Eager service injection | 0 (no DOM impact) | 0 | 0 | [!] OK |
| Lazy service injection with inject() | 0 (no DOM impact) | 0 | 0 | [OK] Good |
LoggerService into another service's constructor?constructor(private logger: LoggerService) {}. Other options have incorrect order or missing keywords.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';
}
}log() method, which returns 'Logged'.@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private authService: AuthService) {}
}
// AuthService is not decorated with @Injectable@Injectable to be injectable into other services or components.@Injectable, so Angular cannot inject it into UserService.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?Pass the test and this pattern moves unknown