Performance: Constructor injection
Constructor injection affects the initialization speed of services and components during app startup, impacting the time to first meaningful paint.
import { Injectable } from '@nestjs/common'; import { SomeDependency } from './some-dependency'; @Injectable() export class MyService { constructor(private readonly dependency: SomeDependency) {} }
import { Injectable, Injector } from '@nestjs/common'; import { SomeDependency } from './some-dependency'; @Injectable() export class MyService { private dependency: SomeDependency; constructor(private injector: Injector) {} async init() { this.dependency = this.injector.get(SomeDependency); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual Injector.get() calls | 0 (no DOM impact) | 0 | Blocks script execution delaying paint | [X] Bad |
| Constructor injection | 0 (no DOM impact) | 0 | Non-blocking synchronous init, faster paint | [OK] Good |
UsersService in a NestJS class?private readonly with the service type for proper injection and immutability.constructor(private readonly usersService: UsersService) {} (A) is correct. B misses access modifier, C misses type, D misses type annotation.appController.getHello() is called?import { Injectable, Controller } from '@nestjs/common';
@Injectable()
class HelloService {
getMessage() {
return 'Hello, NestJS!';
}
}
@Controller()
class AppController {
constructor(private readonly helloService: HelloService) {}
getHello() {
return this.helloService.getMessage();
}
}AppController receives HelloService via constructor injection and stores it as helloService.getHello() calls helloService.getMessage() which returns 'Hello, NestJS!'.@Injectable()
class CatsService {}
@Controller('cats')
class CatsController {
constructor(catsService: CatsService) {}
findAll() {
return 'All cats';
}
}catsService: CatsService lacks an access modifier like private or public, so it won't be assigned as a class property.@Injectable() is present on service, @Controller('cats') has path, and findAll can be sync. So no other errors.AuthService and UsersService, into a NestJS controller. Which constructor correctly injects both services following best practices?private readonly for injected services to keep them immutable and private.private readonly, while others miss modifiers or use public.Pass the test and this pattern moves unknown