How to Inject NEST JS Service from Other Module

Are you facing¬† “Nest can’t resolve dependencies of the [Module] ( ?). Please make sure that the argument [Service] at index [1] is available in the current context”. Read this guide to understand what’s happening and how to avoid this dependency issue in the future.

Let’s assume we have two different modules with separate services inside.

  1. Categories
  2. Products

Now, for some reason, we want to use the Categories service in the products service. First, we have to make sure that both modules are imported into the app module (app.module.ts). So, the app.module.ts file will look like this.

 

Now, we know both modules are available in the app context. In order to import a specific service, we first have to export that service in the relevant module. In our example, we are trying to import CategoriesService into the Products service. So we have to first export the CategoriesService from the categories module (categories.module.ts). We will add the exports array as seen in the code below.

Now, in the final step, we have to import the CategoriesModule in ProductsModule with the help of imports. Check the code below and make sure you are importing CategoriesModule, not CategoryService.

 

This will resolve the dependency issue and you’ll be able to use CategoriesService in ProductsService. By using the same method, you can export and inject services to any other service.

Conclusion

If you want to inject a Nest JS Service into another service, keep these 4 points in mind.

  1. Make sure both modules are imported into app.module.ts
  2. Export the service you want to inject somewhere else from the relevant module.
  3. Import the module whose service you want to inject

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here