Así que tengo una aplicación Nest y me he quedado atascado en lo que parece un problema muy básico.
Necesito usar PlaceVerificationRequestService en PlaceService pero no puedo inyectarlo correctamente sin recibir el siguiente error:
Nest no puede resolver las dependencias de PlaceService (PlaceRepository, ClientService, ?). Asegúrese de que la dependencia del argumento en el índice [2] esté disponible en el contexto de PlaceModule.
Mi enfoque ha sido simplemente seguir el mismo estilo que hice al importar e inyectar ClientService en PlaceService, pero aún así no funciona y no puedo entender por qué.
Este es mi código.
lugar.módulo.ts
@Module({ imports: [ MikroOrmModule.forFeature({ entities: [Place, Client, PlaceVerificationRequest], }), ], providers: [PlaceService, ClientService, PlaceVerificationRequestService], controllers: [PlaceController], exports: [PlaceService], })place-verification-request.module.ts
@Module({ imports: [ MikroOrmModule.forFeature({ entities: [PlaceVerificationRequest, Client, Place], }), ], providers: [PlaceVerificationRequestService, ClientService, PlaceService], controllers: [PlaceVerificationRequestController], exports: [PlaceVerificationRequestService], })lugar.servicio.ts
@Injectable() export class PlaceService { constructor( @InjectRepository(Place) private readonly placeRepo: EntityRepository<Place>, private readonly clientService: ClientService, private readonly reqService: PlaceVerificationRequestService, ) {}Siento que me estoy perdiendo algo que está justo en frente de mi nariz, ya que se siente muy básico, pero parece que no puedo detectarlo. ¿Alguien que tenga una pista? Gracias
Bien, después de 5 horas, el truco es... leer los documentos.
Nest can't resolve dependencies of the <provider> (?). Please make sure that the argument <unknown_token> at index [<index>] is available in the <module> context. Potential solutions: - If <unknown_token> is a provider, is it part of the current <module>? - If <unknown_token> is exported from a separate @Module, is that module imported within <module>? @Module({ imports: [ /* the Module containing <unknown_token> */ ] }) If the unknown_token above is the string dependency, you might have a circular file import.(debo admitir que podrían haber presentado un mensaje de error más claro)
Básicamente, el problema era que PlaceService se inyectaba en PlaceVerificationRequestService y PlaceVerificationRequestService se inyectaba en PlaceService, por lo que el truco es usar forwardRef :
PlaceVerificationRequestService
@Inject(forwardRef(() => PlaceService)) private readonly placeService: PlaceService,PlaceService
@Inject(forwardRef(() => PlaceVerificationRequestService)) private readonly reqService: PlaceVerificationRequestService,Nest no puede averiguar cómo crear una copia de PlaceService porque no ha proporcionado todas las diferentes dependencias de PlaceService.
Es por eso que pregunta si <unknown_token> un proveedor. En otras palabras, ¿el PlaceService necesita una copia de este unknown_token? Ahora eso no tiene sentido para mí, así que lo que probablemente quiera preguntarte es si necesita una copia de ese Servicio de solicitud de verificación de lugar, pero la forma en que escribiste esto te está dando un mensaje confuso, sabes que saldremos de eso. lo que ponemos en él, por lo que el error no es confuso, simplemente le dimos algo que hizo que nos diera un aviso confuso.
Puede intentar escribir una prueba para esto haciendo algo como esto, por ejemplo:
import { Test } from '@nestjs/testing'; import { PlaceService } from './place/service'; import { PlaceVerificationRequestService } from './place-verification-request.service'; it('can create an instance of place service', async () => { // Create a fake copy of the place verification request service const fakePlaceVerificationRequestService = { find: () => Promise.resolve([]) // add properties of the service as arguments create: () => Promise.resolve() }; const module = await Test.createTestingModule({ providers: [ PlaceService, { provide: PlaceVerificationRequestService, useValue: fakePlaceVerificationRequestService } ], }).compile(); const service = module.get(PlaceService); expect(service).toBeDefined(); });