一、注入形式
lazy.module.ts
import { Module } from '@nestjs/common';
import { LazyService } from './lazy.service';
import { LazyController } from './lazy.controller';
@Module({
controllers: [LazyController],
providers: [LazyService],
exports: [LazyService],
})
export class LazyModule {}lazy.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class LazyService {
findAll() {
return `This action returns all lazy`;
}
}
keyword.controller.ts
import {
Controller,
Get,
Inject,
} from '@nestjs/common';
import { LazyModuleLoader } from '@nestjs/core';
import { LazyService } from '../lazy/lazy.service';
@Controller('keyword')
export class KeywordController {
@Inject()
private lazyModuleLoader: LazyModuleLoader;
@Get()
async findOne() {
const { LazyModule } = await import('../lazy/lazy.module');
const moduleRef = await this.lazyModuleLoader.load(() => LazyModule);
const lazyService = moduleRef.get(LazyService);
return lazyService.findAll();
}
}二、app实例获取
const lazyModuleLoader = app.get(LazyModuleLoader);
文章介绍了如何在NestJS应用中实现模块的懒加载,通过`LazyModuleLoader`来延迟加载`LazyModule`,以提高应用性能。在`KeywordController`中,使用`@Inject()`和`import()`动态加载`LazyService`,并在需要时调用其方法。
2368

被折叠的 条评论
为什么被折叠?



