- module 循环依赖
例如 asset.module.ts <-> user.module.ts 循环依赖互相调用的情况, 可以通过在 import 中使用 forwardRef
进行延迟加载
1 2 3 4 5 6 7 8 9 10 11
| @Module({ imports: [ TypeOrmModule.forFeature([AssetEntity]), forwardRef(() => UserModule), ], controllers: [AssetController], providers: [AssetService], exports: [AssetService], }) export class AssetModule {}
|
1 2 3 4 5 6 7 8
| @Module({ imports: [TypeOrmModule.forFeature([User]), forwardRef(() => AssetModule)], providers: [UserService], controllers: [UserController], exports: [UserService], }) export class UserModule {}
|
- service 循环依赖
除了 module 会出现循环依赖, service 一样会. 一样通过 forwardRef
包裹即可
1 2 3 4 5 6 7 8
| @Injectable() export class UserService { constructor( @Inject(forwardRef(() => AssetService)) private assetService: AssetService, ) {} }
|
1 2 3 4 5 6 7 8
| @Injectable() export class AssetService { constructor( @Inject(forwardRef(() => UserService)) private userService: UserService, ) {} }
|