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. 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)

enter image description here

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,
     ) {}
}

Answers:

Answer

The forwardRef function should be used in the imports list, not in the providers, see example in documentation.

Also, you should either use a ModuleRef approach or a forwardRef approach, not both.

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,
  ) {}
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.