All quizzesEasy
Injectable & DI Basics
Preview — 3 of 10 questions
Why do you decorate a service class with @Injectable()?
javascript
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
findAll(): string[] {
return ['Felix', 'Garfield'];
}
}ATo make its methods static
BTo expose it as an HTTP route
CTo automatically persist it to the database
DTo mark it as a provider that the Nest DI container can manage and inject into other classes
What is the idiomatic way to inject a service into another class in NestJS?
javascript
import { Controller, Get } from '@nestjs/common';
import { CatsService } from './cats.service';
@Controller('cats')
export class CatsController {
constructor(private readonly catsService: CatsService) {}
@Get()
findAll(): string[] {
return this.catsService.findAll();
}
}ACall new CatsService() inside the method
BDeclare it as a private readonly constructor parameter and let Nest provide it
CImport it as a global variable
DAttach it to globalThis
You created CatsService. What must you do so it can be injected within its module?
javascript
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
@Module({
controllers: [CatsController],
providers: [CatsService],
})
export class CatsModule {}AAdd it to the module's providers array
BAdd it to the module's controllers array
CNothing — @Injectable() auto-registers it everywhere
DExport it from a barrel index.ts file
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.