Consider this NestJS service that injects a repository via constructor injection. What will be logged when getData() is called?
import { Injectable } from '@nestjs/common'; @Injectable() export class DataService { constructor(private readonly repo: { find: () => string }) {} getData() { return this.repo.find(); } } const fakeRepo = { find: () => 'data found' }; const service = new DataService(fakeRepo); console.log(service.getData());
Constructor injection assigns the passed object to the private readonly property repo.
The DataService receives fakeRepo via constructor injection. The getData() method calls repo.find(), which returns the string "data found".
Choose the correct syntax for injecting MyService into AppService using constructor injection.
Use private readonly to declare and assign the injected service in one step.
Option A uses private readonly which is the recommended pattern in NestJS for constructor injection. It declares and assigns the service as a private readonly property.
Given this service, why does NestJS throw a runtime error about missing dependencies?
import { Injectable } from '@nestjs/common'; @Injectable() export class UserService { constructor(private readonly repo) {} getUser() { return this.repo.findUser(); } }
Check if NestJS can identify the dependency type from the constructor.
Without a type annotation, NestJS cannot know what to inject for repo. The constructor parameter must have a type for NestJS to resolve the dependency.
In this NestJS controller, what will be the value of this.authService.isLoggedIn after the constructor runs?
import { Controller } from '@nestjs/common'; class AuthService { isLoggedIn = false; } @Controller() export class AuthController { constructor(private readonly authService: AuthService) { this.authService.isLoggedIn = true; } }
The constructor sets isLoggedIn to true explicitly.
The authService instance is injected and its isLoggedIn property is set to true in the constructor, so its value is true after instantiation.
Choose the most accurate description of how constructor injection works in NestJS.
Think about how NestJS uses TypeScript metadata to inject services.
NestJS reads the types of constructor parameters and uses its dependency injection container to provide instances automatically. This is the core of constructor injection in NestJS.