Menu
CoddyTech

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 icon

Challenge

Easy
  • Wire the starter's StatsModule so StatsController gets the TasksService that TasksController uses, and import it in AppModule.
  • GET /stats answers { "total", "done", "open" }.
  • Send GET /stats, then POST /tasks with a title, then GET /stats again.

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 {}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in TypeScript and NestJS