[英]How to use Global module in 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 中的服务时非常有用。
如果您想使用一些高频服务(例如prisam,jwt,redis,bull等),您可以:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.