javascript - 使用 forwardRef 时 NestJS Typescript 错误
我正在尝试在同一个模块中将一个提供者用于另一个提供者。循环依赖文档建议使用 forwardRef 函数。然而,在我的模块中,它显示以下错误:
Type 'ForwardReference<any>' is not assignable to type 'Provider<any>'.
Type 'ForwardReference<any>' is not assignable to type 'ExistingProvider<any>'.ts(2322)
这是我的模块:
@Module({
imports: [],
providers: [
forwardRef(() => CartItemService),
forwardRef(() => CartService),
CartResolver,
CartItemResolver,
,
CartModel,
],
exports: [CartService, CartItemService],
})
export class CartModule {}
这就是我提供者的要点
@Injectable()
export class CartService {
constructor(
@Inject(KNEX_CONNECTION) private readonly knex,
@Inject(forwardRef(() => CartItemService))
private readonly cartItem: CartItemService,
) {}
}
答案#1
forwardRef 函数应该用在 imports 列表中,而不是在 providers 中使用,详情请参见文档中的示例。
另外,你应该使用 ModuleRef 方法或 forwardRef 方法,而不是两者都用。
我建议你尝试实现文档中的示例,以确定如何在你的代码中实现它。
你的模块应该是这样的:
@Module({
providers: [
CartItemService,
CartService,
CartResolver,
CartItemResolver,
CartModel,
],
exports: [CartService, CartItemService] //only if this module is imported by other modules
})
export class CartModule {}
你上面那样的服务是可以的:
@Injectable()
export class CartService {
constructor (
@Inject(KNEX_CONNECTION) private readonly knex,
@Inject(forwardRef(() => CartItemService)) private readonly cartItem: CartItemService,
) {}
}
