A Second Module
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 11 of 24.
The new StatsController lives in its own module but needs TasksService, which belongs to TasksModule. A module's providers are private to it until it shares them.
@Module({
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
@Module({
imports: [UsersModule],
controllers: [ProfileController],
})
export class ProfileModule {}exports makes a provider available to other modules, and imports brings in a module's exports. ProfileController can now ask for UsersService and gets the same instance as UsersModule. Listing UsersService in ProfileModule's own providers would start too, but builds a second instance with its own data.
A module's routes only exist once AppModule imports it.
Challenge
EasyA new page of the board shows counts: how many tasks exist, how many are done and how many are open. The starter adds StatsController for it, in its own module, StatsModule. The controller is already written. It only needs the same TasksService that TasksController uses, so both see the same tasks. Three files change, one line each.
- In
src/tasks/tasks.module.ts, share the service: addexportsto the module, listingTasksService. A module's providers stay private to it until it exports them. - In
src/stats/stats.module.ts, addimports, listingTasksModule. NowStatsControllercan ask forTasksServiceand gets the same instance. Do not listTasksServiceinStatsModule's ownproviders. That would build a second service with its own copy of the tasks, and here the app would not even start, becauseTasksServiceneedsClockService. - In
src/app.module.ts, addStatsModuletoimports, next toTasksModule. Nest only creates routes for the modules thatAppModuleimports.
Try it: send GET /stats. You get 200 and:
{ "total": 3, "done": 1, "open": 2 }POST { "title": "Buy milk" } to /tasks, then send GET /stats again:
{ "total": 4, "done": 1, "open": 3 }If the numbers did not change, StatsController got a different service than TasksController.
Try it yourself
import { Module } from '@nestjs/common';
import { StatsController } from './stats.controller';
// StatsController needs TasksService, which belongs to TasksModule.
@Module({
controllers: [StatsController],
})
export class StatsModule {}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in TypeScript and NestJS
Practice on your own: Express playground