【问题标题】:Run program on init在初始化时运行程序
【发布时间】:2019-04-28 00:24:47
【问题描述】:

我会创建一个程序(脚本)在运行时启动操作,所以我没有在这个程序中使用路由

我正在使用NestJS framework(要求)。

实际上我正在尝试在main.ts 文件中编写我的代码并使用我的方法导入服务。

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {AppService} from './app.service'
import { TreeChildren } from 'typeorm';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
let appService: AppService; <- can't use appService methods
this.appService.
bootstrap();

我的服务

@Injectable()
export class AppService {
  constructor(
    @InjectRepository(File) private readonly fileRepository: Repository<File>,
  ) {}

  async getTypes(): Promise<File[]> {
    return await this.fileRepository.find();
  }
}

我会使用服务来处理我的操作,所以我会使用 DI,它在非​​类文件中不起作用。

我会知道如何在初始化时以适当的方式运行我的操作

【问题讨论】:

标签: javascript node.js typescript dependency-injection nestjs


【解决方案1】:

有两种方法可以做到这一点:

A) 生命周期事件

使用Lifecycle Event(类似于 Angular 中的变更检测钩子)运行代码并注入所需的服务,例如:

服务

export class AppService implements OnModuleInit {
  onModuleInit() {
    console.log(`Initialization...`);
    this.doStuff();
  }
}

模块

export class ApplicationModule implements OnModuleInit {
  
  constructor(private appService: AppService) {
  }

  onModuleInit() {
    console.log(`Initialization...`);
    this.appService.doStuff();
  }
}
  

B) 执行上下文

使用 Execution Context 访问 main.ts 中的任何服务:

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

【讨论】:

    猜你喜欢
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2012-03-03
    • 2021-12-17
    • 1970-01-01
    • 2011-11-25
    相关资源
    最近更新 更多