Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

javascript - Run program on init

I would create a program (script) that launches actions when it's get run, so I'm not using routes in this program

I'm using NestJS framework (requirement).

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();

My service

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two ways to do this:

A) Lifecycle Event

Use a Lifecycle Event (similar to change detection hooks in Angular) to run code and inject the services needed for it, e.g.:

Service

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

Module

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

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

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...