简体   繁体   English

如何使用 JSON 中的数据初始化多个 nestjs 提供程序?

[英]How can I initialize multiple nestjs provider with data from JSON?

I'm new to NestJS and am creating an application.我是 NestJS 的新手,正在创建一个应用程序。 My application utilizes the MVC architecture and has multiple modules for example我的应用程序利用 MVC 架构,并且有多个模块,例如

Project
 |
 +-- App.Controller
 +-- App.Service
 +-- App.Module
 |    
 +-- SubModule1
 |  |  
 |  +-- SubModule1.Controller
 |  +-- SubModule1.Service
 |  +-- SubModule1.Module
 |    
 +-- SubModule2
 |  |  
 |  +-- SubModule2.Controller
 |  +-- SubModule2.Service
 |  +-- SubModule2.Module
 |
 +-- SubModule3
 |  |  
 |  +-- SubModule3.Controller
 |  +-- SubModule3.Service
 |  +-- SubModule3.Module

Now each of my submodules service class has a data member现在我的每个子模块服务 class 都有一个数据成员

private member: string[] = []

I would like to initialise these class members with some data that i have stored in a json file.我想用我存储在 json 文件中的一些数据来初始化这些 class 成员。 My json structure is as such我的 json 结构是这样的

{
    'SubModule1' : [
        string1,
        string2,
        string3,
        ...
        stringN
    ], 
    'SubModule2' : [
        string1,
        string2,
        string3,
        ...
        stringN
    ], 
    'SubModule3' : [
        string1,
        string2,
        string3,
        ...
        stringN
    ]
}

Can anyone please guide me as to what is the right way to do this?谁能指导我什么是正确的方法? Where should i load the json and then inject the data?我应该在哪里加载 json 然后注入数据? My initial thoughts were to Utilize the app.service class to load and inject data, but i am unsure as to how can i access the submodule providers.我最初的想法是利用 app.service class 来加载和注入数据,但我不确定如何访问子模块提供程序。

Any guidance or help will be much appreciated.任何指导或帮助将不胜感激。 Thank you谢谢

For initializing data during the start of your application, you can use one of the lifecycle events , for example OnModuleInit :为了在应用程序启动期间初始化数据,您可以使用生命周期事件之一,例如OnModuleInit

@Injectable()
export class MyService implements OnModuleInit {
  onModuleInit() {
    await initializeData()
  }
}

If you want to do that repeatedly for many provider of the same structure, you can extends from an initializer class like so:如果您想为相同结构的许多提供者重复执行此操作,您可以从初始化程序 class 扩展,如下所示:

abstract class DataInitializer implements OnModuleInit {
  member: string[];
  onModuleInit() {
    const jsonData = // ...
    this.member= jsonData[this.constructor.name];
  }
}

@Injectable()
export class AppService extends DataInitializer {
  // ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM