A Second Module
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 8 of 17.
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
Easy- Wire the starter's
StatsModulesoStatsControllergets theTasksServicethatTasksControlleruses, and import it inAppModule. GET /statsanswers{ "total", "done", "open" }.- Send
GET /stats, thenPOST /taskswith a title, thenGET /statsagain.
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.