首页 > 解决方案 > 如何在 NestJs 中使用全局模块

问题描述

我正在使用nest js作为后端。对于这个项目,我开始使用 NestJs,在文档中我发现在 nestJs 中我们可以构建Global Modules. 所以我的全局模块如下所示:

//Module
import {Global, Module} from "@nestjs/common";
import {GlobalController} from "./global.controller";
import {GlobalService} from "./global.service";
@Global()
@Module({
  imports:[],
  exports:[GlobalService],
  providers:[GlobalService],
  controllers:[GlobalController]
})
export class GlobalModule {}

//Controller
import { Controller, Get } from "@nestjs/common";
import {GlobalService} from "./global.service";
@Controller()

export class GlobalController {
    constructor(private readonly getGlobalData: GlobalService) {
    }
    @Get('global')
    getGlobal(){
        return this.getGlobalData.getGlobalData()
    }
}

//Service
import { Injectable } from "@nestjs/common";
@Injectable()
export class GlobalService {
    private readonly global = [1,12,2]
    getGlobalData(){
     return this.global.map(d => d)
    }
}

在我的根模块中,我注册了我的全局模块:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import {GlobalModule} from "./globalModule/global.module";

@Module({
  imports: [GlobalModule], //register global module
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

现在模块正在工作,当我去时,我从数组中..../global获取我的数据。global我如何理解我们可以创建全局模块以避免在每个模块中重复相同的代码。
问题: 根据我的示例,我如何在不同的模块中使用我的全局模块?

标签: javascriptnode.jsnestjs

解决方案


如果您想在其他模块上使用该 GlobalModule,您必须在您的根模块上导入该模块,如下所示:

import { Module } from '@nestjs/common';
import { AppService } from './app.service';
import { AppController } from './app.controller';
import { OtherModule } from "./otherModule/other.module";
import { GlobalModule } from "./globalModule/global.module";

@Module({
  imports: [GlobalModule, OtherModule], //Import the other module
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

然后在您的其他模块中,您将能够在不导入 GlobalModule 的情况下使用 GlobalService,这在您需要轻松使用 Guard 中的服务时非常有用。


推荐阅读