How Providers Work in Nest.js
Swipe um das Menü anzuzeigen
Previously, you learned that Nest.js can inject dependencies automatically. But how does Nest.js know which classes it can create?
To make a class available for dependency injection, you mark it with the @Injectable() decorator.
@Injectable()
export class UsersService {}
Next, register the service inside a module using the providers array.
@Module({
providers: [UsersService],
})
Here is what is happening:
@Injectable()tells Nest.js that the class can be managed by the framework;providersregisters the service with the module;- Nest.js creates a single instance of the service;
- Whenever another class requests
UsersService, Nest.js provides the same instance automatically.
For example, the controller can now receive the service through its constructor:
constructor(private usersService: UsersService) {}
This system keeps your application organized by allowing different parts of your code to work together without manually creating or managing objects.
War alles klar?
Danke für Ihr Feedback!
Abschnitt 4. Kapitel 2
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen
Abschnitt 4. Kapitel 2