I want to use something like this:
cats.interface.ts
export interface ICats {
meow(): void
}
cats.service.ts
@Injectable()
export class CatsService implements ICats {
constructor()
meow(): void {
return;
}
}
cats.module.ts
@Module({
providers: [CatsService]
exports: [CatsService]
})
export class CatsModule {}
animals.service.ts
@Injectable()
export class AnimalsService {
constructor(@Inject('ICats') private readonly cats: ICats)
test(): void {
return this.cats.meow();
}
}
animals.module.ts
@Module({
imports: [CatsModule],
providers: [AnimalsService],
exports: [AnimalsService]
But receive
Nest can't resolve dependencies of the
CodePudding user response:
You can use @Inject('ICats')
, but you have to register that injection token with the DI container. To do this, you can use a custom provider like so:
@Module({
providers: [
{
provide: 'ICats',
useClass: CatsService
}
],
exports: ['ICats'],
})
export class CatsModule {}
Interfaces on their own are not enough, because there is no metadata about them like there is about classes. Without that metadata, Nest won't know what to inject, which is why we have to use the manual @Inject()