nestjseventemitter

Call 1 function twice with event emitter with nestjs problem


This is my code: event-emitter.module.ts

import { Module } from '@nestjs/common';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { EmitterService } from './event-emitter.service';

@Module({
  imports: [EventEmitterModule.forRoot()],
  providers: [EmitterService],
  exports: [EmitterService],
})
export class EmitterModule {}

event-emitter.service.ts

import { Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class EmitterService {
  constructor(private eventEmitter: EventEmitter2) {}

  emitEvent() {
    console.log('first');
    this.eventEmitter.emit('msg.sent');
  }

  @OnEvent('msg.sent')
  listentToEvent() {
    console.log('second');
  }
}

test.controller.ts

import { Controller, Get } from '@nestjs/common';
import { EmitterService } from '../event-emitter/event-emitter.service';

@Controller('test')
export class TestController {
  constructor(private readonly emitterService: EmitterService) {}

  @Get('/event-emitter')
  async testEventEmitter() {
    this.emitterService.emitEvent();
  }
}

When I use event emitter service, there are 2 options which I use for module and each option log different result:

The 1st option: test.module.ts

import { Module } from '@nestjs/common';
import { EmitterModule } from '../event-emitter/event-emitter.module';
import { EmitterService } from '../event-emitter/event-emitter.service';
import { TestController } from './test.controller';

@Module({
  imports: [],
  controllers: [TestController],
  providers: [EmitterService],
  exports: [],
})
export class TestModule {}

1st result: enter image description here

The 2nd option: test.module.ts

import { Module } from '@nestjs/common';
import { EmitterModule } from '../event-emitter/event-emitter.module';
import { EmitterService } from '../event-emitter/event-emitter.service';
import { TestController } from './test.controller';

@Module({
  imports: [EmitterModule],
  controllers: [TestController],
  providers: [],
  exports: [],
})
export class TestModule {}

The 2nd result: enter image description here

I don't know why the first option call listentToEvent() 2 times. Thank for your attention.


Solution

  • You need to place your event handler function in a different service file. If your event is being emitted in one service file, the handler of @OnEvent decorator method should be in another file. If these are in same file, it will behave abnormally. As mentioned in the nest js documentation:

    enter image description here