Nestjs 学习系列基础篇6 - 模块化Modules

180 阅读1分钟

Nestjs 学习系列基础篇6 - 模块化Modules

  • 如何创建一个模块
  • 如何实现跨模块

nest6_1.png

创建公共模块

src/shared/system.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class SystemService {
  test() {
    return { text: 'test system-service' };
  }
}

src/shared/shared.module.ts

import { Module } from '@nestjs/common';
import { SystemService } from './system.service';

@Module({
  // 注册 
  providers: [SystemService],
  // 暴露 config 模块
  exports: [SystemService],
})
export class SharedModule {}

使用公共模块

假定【 user 】模块需要调用公共模块 【shared】

src/user/user.module.ts

import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { SharedModule } from 'src/shared/shared.module';

@Module({
  controllers: [UserController],
  providers: [UserService],
  // 引用公共模块「SharedModule」
  imports: [SharedModule],
})
export class UserModule {}

src/user/user.service.ts

import { SystemService } from '../shared/system.service';

export class UserService {
  constructor(
    // 模块注入
    private readonly systemService: SystemService,
  ) {}

  create(createUserDto: CreateUserDto) {
    // 测试 SystemService
    console.log('system', this.systemService.test());
    ....
  }
}

项目仓库地址

仓库地址Github: dome-server

注意:基础篇的的代码在 base 分支下