简体   繁体   中英

Module Resolution in nestjs

I have module a and module b . Module a instantiates its service providers asynchronously whilst module b instantiates synchronously. Both contain multiple endpoints. Both modules are imported by the AppModule .

Now I'm new to thinking of things from the server side and I'm also coming from angular lazy loading, so bear with me here.

If an endpoint from module b is activated(?) does module a load as well? Do the service providers defined in module a , that use async factories to instantiate, get instantiated as well?

The concept of async providers is a bit different from Angular's; it has nothing to do with the routes or controllers.

If a provider is async, it means it needs to wait for an asynchronous resource (Promise) to be resolved before it can be instantiated. That can be waiting for a database connection to be established or a configuration to be loaded from the file system. When your application has started, all your async providers have been fully instantiated.


To try this out, you can add the HttpModule asynchronously as follows:

HttpModule.registerAsync({
  useFactory: async () => {
    console.log('Starting to instantiate');
    // wait 5 seconds to simulate asynchronous task
    await new Promise(resolve => setTimeout(resolve, 5000));
    console.log('Done after 5 seconds');
    return {};
  },
}),

],

When you start the application, you will see that the startup will wait the 5 seconds. The HttpModule is not instantiated dynamically as you might expect coming from Angular.

[Nest] 242   - 3/18/2019, 2:08:04 PM   [NestFactory] Starting Nest application...
Starting to instantiate
[Nest] 242   - 3/18/2019, 2:08:04 PM   [InstanceLoader] AppModule dependencies initialized +8ms
Done after 5 minutes
[Nest] 242   - 3/18/2019, 2:08:09 PM   [InstanceLoader] HttpModule dependencies initialized +5004ms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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