javascript - 如何在 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
我如何理解我们可以创建全局模块以避免在每个模块中重复相同的代码。
问题: 根据我的示例,我如何在不同的模块中使用我的全局模块?
解决方案
如果您想在其他模块上使用该 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 中的服务时非常有用。
推荐阅读
- angular - apereo CAS 到 Angular/Spring 启动应用程序
- javascript - 如何解码 urllib 响应数据
- c# - 向代码中添加新行时如何侦听来自 DTE 对象的事件
- c++ - CTabCtrl ItemAction & ItemState
- java - 如何调整 Android MediaCodec 使用的输入和输出缓冲区的大小?
- sockets - Log4cplus:SocketAppender 有加密选项吗?
- kubernetes - 大三角帆使用舵图在默认命名空间中创建应用程序
- vba - 使用 VBA 重命名动态块可见性状态
- dns - 无法在 Kubernetes 中使用 ACME DNS01 挑战提供程序创建通配符让我们加密
- javascript - ng-model 不接受通过 jquery 时间选择器输入的值;