Javascript 在init上运行程序
我会创建一个程序(脚本),在运行时启动操作,所以我不会在这个程序中使用路由 我正在使用(要求) 实际上,我正在尝试在Javascript 在init上运行程序,javascript,node.js,typescript,dependency-injection,nestjs,Javascript,Node.js,Typescript,Dependency Injection,Nestjs,我会创建一个程序(脚本),在运行时启动操作,所以我不会在这个程序中使用路由 我正在使用(要求) 实际上,我正在尝试在main.ts文件中编写代码,并使用我的方法导入服务 import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import {AppService} from './app.service' import { TreeChildren } from 'typeorm'
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();
从'@nestjs/core'导入{NestFactory};
从“./app.module”导入{AppModule};
从“/app.service”导入{AppService}
从“typeorm”导入{TreeChildren};
异步函数引导(){
const app=wait NestFactory.create(AppModule);
等待应用程序。聆听(3000);
}
let-appService:appService 有两种方法可以做到这一点:
A) 生命周期事件
使用(类似于Angular中的change detection Hook)运行代码并注入所需的服务,例如:
服务
模块
B) 执行上下文
使用访问main.ts中的任何服务:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
const appService = app.get(AppService);
}
有一个OnModuleInit钩子,你可以将它应用到AppModuler上。告诉你这是一种方法,同时我发现了执行上下文:
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();
}
}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
const appService = app.get(AppService);
}