简体   繁体   English

使用 forwardRef 时出现 NestJS Typescript 错误

[英]NestJS Typescript error when use forwardRef

I'm trying to use a provider into another provider within the same module.我正在尝试将一个提供者用于同一模块中的另一个提供者。 The Circular doc is suggesting to use forwardRef function. Circular 文档建议使用forwardRef函数。 However, in my module, it shows the below error:但是,在我的模块中,它显示以下错误:

Type 'ForwardReference<any>' is not assignable to type 'Provider<any>'.
  Type 'ForwardReference<any>' is not assignable to type 'ExistingProvider<any>'.ts(2322)

在此处输入图片说明

Here is my module:这是我的模块:

@Module({
  imports: [],
  providers: [
    forwardRef(() => CartItemService),
    forwardRef(() => CartService),
    CartResolver,
    CartItemResolver,
    ,
    CartModel,
  ],
  exports: [CartService, CartItemService],
})
export class CartModule {}

And here is the gist of my provider这是我的提供者的要点

@Injectable()
export class CartService {
  constructor(
    @Inject(KNEX_CONNECTION) private readonly knex,
    @Inject(forwardRef(() => CartItemService))
    private readonly cartItem: CartItemService,
     ) {}
}

The forwardRef function should be used in the imports list, not in the providers , see example in documentation . forwardRef函数应该在imports列表中使用,而不是在providers ,请参阅文档中的示例

Also, you should either use a ModuleRef approach or a forwardRef approach, not both.此外,您应该使用 ModuleRef 方法或 forwardRef 方法,而不是两者都使用。

I suggest you try and implement the example in the documentation to determine how to implement it in your code.我建议您尝试实现文档中的示例,以确定如何在您的代码中实现它。

Your module should be something like this:你的模块应该是这样的:

@Module({
  providers: [
    CartItemService,
    CartService,
    CartResolver,
    CartItemResolver,
    CartModel,
  ],
  exports: [CartService, CartItemService] //only if this module is imported by other modules
})
export class CartModule {}

The service as you did above is fine:你上面做的服务很好:

@Injectable()
export class CartService {
  constructor (
    @Inject(KNEX_CONNECTION) private readonly knex,
    @Inject(forwardRef(() => CartItemService)) private readonly cartItem: CartItemService,
  ) {}
}

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

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