我将创建一个程序(脚本),该程序在运行时会启动操作,因此我不在此程序中使用路由
我正在使用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,该DI在非类文件中不起作用.
我会知道如何以适当的方式在初始化时间内运行我的操作
解决方法:
有两种方法可以做到这一点:
执行上下文
使用Execution Context访问任何服务:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
const appService = app.get(AppService);
}
生命周期事件
使用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();
}
}
原文地址:https://codeday.me/bug/20191013/1906235.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。