Introduction
Optional providers let you use a service only if it is available. This helps your app work even if some parts are missing.
Optional providers let you use a service only if it is available. This helps your app work even if some parts are missing.
constructor(@Optional() private readonly service?: ServiceType) {}import { Optional, Injectable } from '@nestjs/common'; @Injectable() export class MyService { constructor(@Optional() private readonly logger?: LoggerService) {} logMessage(msg: string) { this.logger?.log(msg); } }
constructor(@Optional() private readonly cacheService?: CacheService) {}This example shows how MyService works with and without the LoggerService. When the logger is present, it logs a message. Otherwise, it prints a fallback message.
import { Injectable, Optional } from '@nestjs/common'; @Injectable() class LoggerService { log(message: string) { console.log('Log:', message); } } @Injectable() class MyService { constructor(@Optional() private readonly logger?: LoggerService) {} doWork() { if (this.logger) { this.logger.log('Work started'); } else { console.log('No logger available'); } } } // Simulate NestJS container const serviceWithLogger = new MyService(new LoggerService()); const serviceWithoutLogger = new MyService(); serviceWithLogger.doWork(); serviceWithoutLogger.doWork();
Always check if the optional provider exists before using it to avoid errors.
Optional providers help make your code more flexible and easier to test.
Use @Optional() to mark providers that may not be available.
Check if the provider exists before calling its methods.
Optional providers help your app handle missing dependencies gracefully.
@Optional() in a NestJS provider?@Optional() with parentheses.MyService is NOT provided in the module?
constructor(@Optional() private readonly myService?: MyService) {}
useService() {
return this.myService ? 'Service available' : 'Service missing';
}myService exists. Since it's undefined, it returns "Service missing".constructor(@Optional() private readonly service: MyService) {
this.service.doSomething();
}this.service.doSomething() without checking if service exists can cause runtime error.export class MyComponent {
constructor(@Optional() private readonly logger?: LoggerService) {}
logMessage(msg: string) {
// What should you do here?
}
}this.logger exists before calling log() to avoid errors.Pass the test and this pattern moves unknown