在 init 上运行程序

inf*_*dev 5 javascript dependency-injection node.js typescript nestjs

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

我正在使用NestJS 框架(要求)。

实际上,我正在尝试将代码写入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();
Run Code Online (Sandbox Code Playgroud)

我的服务

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

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

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

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

Kim*_*ern 24

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

A) 生命周期事件

使用生命周期事件(类似于 Angular 中的更改检测挂钩)来运行代码并注入所需的服务,例如:

服务

export class AppService implements OnModuleInit {
  onModuleInit() {
    console.log(`Initialization...`);
    this.doStuff();
  }
}
Run Code Online (Sandbox Code Playgroud)

模块

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

  onModuleInit() {
    console.log(`Initialization...`);
    this.appService.doStuff();
  }
}
  
Run Code Online (Sandbox Code Playgroud)

B) 执行上下文

使用执行上下文访问 main.ts 中的任何服务:

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