问题描述
我会创建一个程序(脚本),当它运行时启动动作,所以我没有在这个程序中使用路由
I would create a program (script) that launches actions when it's get run, so I'm not using routes in this program
我正在使用 NestJS 框架(要求).
I'm using NestJS framework (requirement).
实际上我正在尝试在 main.ts
文件中编写我的代码并使用我的方法导入服务.
Actually I'm trying to write my code in main.ts
file and importing a service with my methods .
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,它在非类文件中不起作用.
I would use services to treat my operations so I sould use DI, which is not working in a non class file.
我会知道如何在初始化时以正确的方式运行我的操作
I would know how to run my operations in init time in a proper way
推荐答案
有两种方法可以做到这一点:
There are two ways to do this:
使用 生命周期事件(类似于 Angular 中的更改检测钩子) 运行代码并注入所需的服务,例如:
Use a Lifecycle Event (similar to change detection hooks in Angular) to run code and inject the services needed for it, e.g.:
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) 执行上下文
使用 执行上下文 来访问您的 main.js 中的任何服务.ts:
B) Execution Context
Use the Execution Context to access any service in your main.ts:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
const appService = app.get(AppService);
}
这篇关于在 init 上运行程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!