一、关于 NestJS 中的模块

  • 模块是具有 @Module() 装饰器的类。 @Module() 装饰器提供了元数据,Nest 用它来组织应用 程序结构
  • https://docs.nestjs.com/modules

image.png

  • 每个 Nest 应用程序至少有一个模块,即根模块。根模块是 Nest 开始安排应用程序树的地方。事实上,根模块可能是应用程序中唯一的模块,特别是当应用程序很小时,但是对于大型程序来说这是没有意义的。在大多数情况下,您将拥有多个模块,每个模块都有一组紧密相关的功能
  • @module() 装饰器接受一个描述模块属性的对象: | providers | 由 Nest 注入器实例化的提供者,并且可以至少在整个模块中共享 | | —- | —- | | controllers | 必须创建的一组控制器 | | imports | 导入模块的列表,这些模块导出了此模块中所需提供者 | | exports | 由本模块提供并应在其他模块中可用的提供者的子集。 |

二、NestJS 中创建模块

  1. // 1.创建模块
  2. nest g module module/admin // 后端模块
  3. nest g module module/api // api接口模块
  4. nest g module module/default // 前台模块
  5. // 2.创建控制器
  6. nest g controller module/admin/controller/user
  7. nest g controller module/api
  8. // 3.编写接口
  9. import { Controller, Get } from '@nestjs/common';
  10. @Controller('admin/user') // 把地址加个admin用来区分后台接口,因为前台也有可能有相同名字的接口,这样好区分,不会乱
  11. export class ApiController {
  12. @Get()
  13. index() { // admin/user
  14. return { 'result': '我是api接口' }
  15. }
  16. @Get('user-api')
  17. userIndex() { // admin/user/user-api
  18. return { 'result': '我是user 列表api接口' }
  19. }
  20. }

image.png

三、NestJS 在模块中使用服务

  1. // 1.创建服务,当前这个服务属于mall
  2. nest g service module/admin/service/mall
  3. import { Injectable } from '@nestjs/common';
  4. @Injectable()
  5. export class MallService {
  6. getMalls() {
  7. return [
  8. { "title": "新闻111" },
  9. { "title": "新闻222" }
  10. ]
  11. }
  12. }
  13. // 2.在mall控制器使用mall服务
  14. import { MallService } from './../../service/mall/mall.service'; // 引入mall服务
  15. import { Controller, Get } from '@nestjs/common';
  16. @Controller('admin/mall')
  17. export class MallController {
  18. constructor(private mallService: MallService) { } // 依赖注入
  19. @Get()
  20. index() {
  21. console.log(this.mallService.getMalls()) // 使用 mall 服务返回回来的数据
  22. return '我是admin模块里面mall的页面';
  23. }
  24. }

四、NestJS 中的共享模块

  • 实际上,每个模块都是一个共享模块。一旦创建就能被任意模块重复使用。假设我们将在几个模块之间共享 CatsService 实例。 我们需要把 CatsService 放到 exports 数组中,如下所示: ```typescript

import { Module } from ‘@nestjs/common’; import { CatsController } from ‘./cats.controller’; import { CatsService } from ‘./cats.service’;

@Module({ controllers: [CatsController], providers: [CatsService], // 注入 CatsService 服务 exports: [CatsService], // 把 CatsService 服务暴露出去 }) export class CatsModule {} ```