#@nestjs/event-emitter @OnEvent decorator does not register listener

3 messages · Page 1 of 1 (latest)

quaint lily
#
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AppService } from './app.service';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const appService = app.get(AppService);
  appService.emit();
}
bootstrap();```

```// app.module.ts
import { Module } from '@nestjs/common';
import { AppService } from './app.service';
import { EventEmitterModule } from '@nestjs/event-emitter';

@Module({
  imports: [EventEmitterModule.forRoot()],
  providers: [AppService],
})
export class AppModule {}```

```// app.service.ts
import { Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class AppService {
  constructor(private emitter: EventEmitter2) {}

  @OnEvent('hello_world')
  handleHelloWorld() {
    console.log('Hello World!');
  }

  emit() {
    console.log('AppService.emit()');
    const res = this.emitter.emit('hello_world');
    console.log(res);
  }
}```

i expected that when application starts it will emit `hello_world` event and `handleHelloWorld` method will fire on this event, but it doesn't =/
what am i doing wrong?
lament karma
#

Could be a very very strange race condition where the emit happens but the handler isn't called by the time the application closes

quaint lily
#

i missed await app.init() in the main.ts, now it works.
but may be there is another way to "start" the application after it initializes? i suppose i could use onApplicationBootstrap but may be there is something better?