Performance: Injecting services into components
This affects the initial load time and runtime responsiveness by controlling how dependencies are created and shared in Angular components.
import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-example', templateUrl: './example.component.html' }) export class ExampleComponent { constructor(private dataService: DataService) {} } // DataService is providedIn: 'root' in its @Injectable decorator
import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-example', templateUrl: './example.component.html', providers: [DataService] }) export class ExampleComponent { constructor(private dataService: DataService) {} }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Service provided in component | No direct DOM impact | No reflows triggered | No paint cost | [X] Bad - increases CPU and memory usage |
| Service provided in root | No direct DOM impact | No reflows triggered | No paint cost | [OK] Good - efficient reuse of service instances |
DataService into an Angular standalone component using the new inject() function?const dataService = inject(DataService); inside the class body is the correct pattern.import { Component, inject } from '@angular/core';
import { LoggerService } from './logger.service';
@Component({
selector: 'app-sample',
standalone: true,
template: `Check console
`,
providers: [LoggerService]
})
export class SampleComponent {
private logger = inject(LoggerService);
constructor() {
this.logger.log('Hello from SampleComponent');
}
}AuthService:import { Component, inject } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-login',
standalone: true,
template: `Login
`
})
export class LoginComponent {
private auth = inject(AuthService);
constructor() {
console.log(this.auth.isLoggedIn());
}
}UserService into two standalone components, ProfileComponent and SettingsComponent, so they share the same instance of the service. How should you provide UserService to achieve this?Pass the test and this pattern moves unknown