import { Injectable, Controller, Get } from '@nestjs/common'; @Injectable() export class GreetingService { getGreeting() { return 'Hello, NestJS!'; } } @Controller() export class GreetingController { constructor(private readonly greetingService: GreetingService) {} @Get() greet() { console.log(this.greetingService.getGreeting()); return this.greetingService.getGreeting(); } }
The GreetingService is marked with @Injectable(), so NestJS can inject it into the controller's constructor. The greet method calls getGreeting() which returns the string Hello, NestJS!. This string is logged and returned.
AuthService into a controller. Which constructor syntax is correct?In NestJS, to inject a service via constructor, you must use an access modifier like private or public. Using private readonly is a common best practice to prevent reassignment. Option A uses private readonly which is correct.
LoggerService?import { Injectable, Controller } from '@nestjs/common'; @Injectable() export class LoggerService { log(message: string) { console.log(message); } } @Controller() export class AppController { constructor(private readonly loggerService: LoggerService) {} someMethod() { this.loggerService.log('Test'); } }
Even though LoggerService is marked with @Injectable(), NestJS needs it to be registered in the module's providers array to inject it. If it's missing there, NestJS throws a runtime error about missing provider.
this.configService.apiKey inside AppService after the app starts?import { Injectable, Module } from '@nestjs/common'; @Injectable() export class ConfigService { apiKey = '12345'; } @Injectable() export class AppService { constructor(public readonly configService: ConfigService) {} getApiKey() { return this.configService.apiKey; } } @Module({ providers: [ConfigService, AppService], exports: [AppService] }) export class AppModule {}
The ConfigService has a property apiKey initialized to '12345'. It is injected into AppService correctly via constructor. So, calling getApiKey() returns '12345'.
scope: Scope.REQUEST compared to the default singleton scope?By default, NestJS services are singletons, meaning one instance is shared globally. When a service is marked with scope: Scope.REQUEST, NestJS creates a new instance of that service for every incoming HTTP request, isolating state per request.