Asking
Asking

Reputation: 4192

How to use Global module in NestJs

I am using nest js for back-end. For this project i started to use NestJs, and in the documentation i found that in nestJs we can build Global Modules. So my global module looks like this:

//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)
    }
}

In my root module i registered my global module:

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 {}

Now the module is working, and when i go to ..../global i get my data from global array. How i understand we can create global module to avoid repeating the same code in each module.
Question: According to my example how can i use my global module in different modules?

Upvotes: 5

Views: 23538

Answers (2)

Juan Rambal
Juan Rambal

Reputation: 629

If you want to use that GlobalModule on other module you must import that module on your root module like this:

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 {}

Then in your other module you will be able to use the GlobalService without importing the GlobalModule, this is very useful when you need to use a service inside a Guard easily.

Upvotes: 7

RiverRay
RiverRay

Reputation: 129

if you want to use some service of high frequency (such as prisam,jwt,redis,bull et al), you can just :

  1. put these all service in a globalModule
  2. registed globalModule in root module
  3. use these services in any other module without import global module again and again.

Upvotes: -2

Related Questions