Consider a service class in NestJS decorated with @Injectable(). What is the main effect of this decorator on the service?
import { Injectable } from '@nestjs/common'; @Injectable() export class MyService { getMessage() { return 'Hello from service'; } }
Think about what NestJS needs to do to create and share instances of this class.
The @Injectable() decorator tells NestJS that this class can be managed by its dependency injection system. This allows other classes to receive instances of this service automatically.
In NestJS, you can specify the scope of an injectable provider. Which of the following code snippets correctly sets the scope to Scope.REQUEST?
Check how the scope option is passed as an object property.
The correct syntax is to pass an object with a scope property set to Scope.REQUEST. Option C correctly imports Scope and uses it inside the object.
Given the following code, why does NestJS throw an error that MyService is not a provider?
import { Injectable } from '@nestjs/common'; export class MyService { getData() { return 'data'; } } import { Controller, Get } from '@nestjs/common'; @Controller() export class MyController { constructor(private readonly myService: MyService) {} @Get() get() { return this.myService.getData(); } }
Think about what NestJS requires to manage a class as a provider.
Without the @Injectable() decorator, NestJS does not treat the class as a provider and cannot inject it into other classes.
Consider this NestJS service with transient scope injected twice into a controller. What will be the output of the following code?
import { Injectable, Scope } from '@nestjs/common'; @Injectable({ scope: Scope.TRANSIENT }) export class TransientService { id = Math.random(); } import { Controller, Get } from '@nestjs/common'; @Controller() export class TestController { constructor( private readonly service1: TransientService, private readonly service2: TransientService ) {} @Get() getIds() { return { id1: this.service1.id, id2: this.service2.id }; } }
Recall what transient scope means for service instances.
Transient scope means a new instance is created every time the service is injected. So service1 and service2 are different instances with different random ids.
Choose the most accurate description of what the @Injectable() decorator does in NestJS.
Focus on how NestJS manages class instances and sharing.
The @Injectable() decorator marks a class as a provider so NestJS can create and inject instances automatically. It does not bind routes or disable injection.