반응형

In NestJS, providers are a fundamental concept of the Dependency Injection (DI) system.

Providers are classes or values that are defined within the module and can be injected into other classes

(components, controllers, other providers) within the same module or in other modules.

 

In other words, providers are objects or functions that can be injected into other objects or functions to provide them with some functionality or data. Providers are used to manage the dependencies of your application and to promote code reuse by allowing you to define and share common services across multiple components or modules.

 

To define a provider in NestJS, you need to use the @Injectable() decorator.

This decorator tells the NestJS DI system that the class can be injected into other classes as a dependency.

Once a provider is defined, it can be injected into other classes using the constructor() function.

Here's an example of a simple provider:

 

@Injectable()
export class LoggerService {
  log(message: string) {
    console.log(message);
  }
}

 

 

In this example, the LoggerService class is defined as a provider using the @Injectable() decorator.

This means that it can be injected into other classes that require a logging service.

The log() method can be called to log a message to the console.

To use this provider in another class, you can inject it in the constructor like this:

@Injectable()
export class MyService {
  constructor(private readonly logger: LoggerService) {}

  doSomething() {
    this.logger.log('Doing something...');
  }
}

In this example, the MyService class injects the LoggerService provider in the constructor.

The doSomething() method can then call the log() method of the logger to log a message.

 

Providers are a powerful feature of NestJS that allow you to build modular and reusable applications.

+ Recent posts