【问题标题】:What's the best way to run method of Component (Service) just after bootstrap running?在引导运行后运行组件(服务)方法的最佳方法是什么?
【发布时间】:2018-07-21 01:25:26
【问题描述】:

我使用 NestJS 实例作为微服务(没有 HTTP)。

我需要在引导初始化之后运行带有一些业务逻辑的无限循环组件的方法。

最好的方法是什么?

src/main.ts

import {NestFactory} from '@nestjs/core';
import {ApplicationModule} from './app.module';
import {Transport} from '@nestjs/microservices';

async function bootstrap() {
    const app = await NestFactory.create(ApplicationModule);
    app.connectMicroservice({
        transport: Transport.REDIS,
        url: 'redis://:redis_pass@localhost:6379',
    });
    await app.startAllMicroservicesAsync();

    // Probably here I must run startLoop method from app.service.ts
    
}
bootstrap();

src/app.service.ts

import { Component } from '@nestjs/common';

@Component()
export class AppService {

    startLoop() {
        let timerId = setTimeout(function loop() {
            console.log('Loop process');
            // Some business logic here
            timerId = setTimeout(loop, 1000);
        }, 1000);
    }

}

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    我想说你应该实现OnModuleInit 接口,阅读更多关于生命周期钩子here

    【讨论】:

    猜你喜欢
    • 2013-04-27
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多