Leveraging functionality from an imported module - NestJS

Currently, I am utilizing a service from a services module within the main scaffolded app controller in NestJS.

Although it is functioning as expected - with helloWorldsService.message displaying the appropriate greeting in the @Get method - I can't help but notice that the imports of HelloWorldsService in both app.module and app.controller appear redundant. This seems to go against the encapsulation concept of the services by the services module.

Am I approaching this correctly? Is this the proper way to consume a discrete service from a different module, or is there something that I'm overlooking? My confusion stems from the fact that if this approach is correct, where we have to directly reference other classes (such as referencing HelloWorldService directly in the controller), then the purpose of the providers/imports properties in the @Module declaration becomes unclear.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { RouterModule } from './router/router.module';
import { ServicesModule } from './services/services.module'; //<-- import service MODULE
import { EventsModule } from './events/events.module';
import { HelloWorldsService } from './services/hello-worlds/hello-worlds.service'; //<-- import service module SERVICE


@Module({
  imports: [RouterModule, ServicesModule, EventsModule],
  controllers: [AppController],
  providers: [AppService, HelloWorldsService],
})
export class AppModule {}


//Controller code:
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { HelloWorldsService } from './services/hello-worlds/hello-worlds.service'; //<-- importing service again in consuming controller

@Controller()
export class AppController {
  constructor(private readonly appService: AppService, private readonly helloWorldsService: HelloWorldsService ) {}

    @Get()
    getHello(): string {
        return this.helloWorldsService.Message();
    }
}


//services.module
import { Module } from '@nestjs/common';
import { WagerAccountService } from './wager-account/wager-account.service';
import { WagerAccountHttpService } from './wager-account.http/wager-account.http.service';
import { CustomerIdentityHttpService } from './customer-identity.http/customer-identity.http.service';
import { HelloWorldsService } from './hello-worlds/hello-worlds.service';

@Module({
    exports:[HelloWorldsService],
  providers: [CustomerIdentityHttpService, WagerAccountService, WagerAccountHttpService, CustomerIdentityHttpService, HelloWorldsService]
})
export class ServicesModule {}

Answer №1

If you are looking to utilize certain services within another service, there are several methods available depending on your specific needs. For instance, let's say you have App1Service and App1Module, as well as App2Service and App2Module, and you want to integrate App2Service into App1Service.

  1. You can utilize the providers method.
// App1Module.ts
@Module({
 imports: [],
 controllers: [App1Controller],
 providers: [App1Service, App2Service], // only importing service here
})
export class App1Module {}
  1. Import the entire Module, ensuring to also export the service.
// App1Module.ts
@Module({
 imports: [App2Module], // importing Full Module here
 controllers: [App1Controller],
 providers: [App1Service], // no need to import service here but make sure to export App2Module services
})
export class App1Module {}

App2Service MUST be exported in App2Module.

// App2Module.ts
@Module({
  imports: [],
  controllers: [App2Controller],
  providers: [App2Service],
  exports: [App2Service] // this service is now exported and accessible in other services
})
export class App2Module {}

If you have dependencies within App2Module to other Modules, such as App3Module, and wish to employ App3Service in App1Service, you should follow Option 2. Export App3Service in App3Module so it becomes automatically available for App1Service. Here's how it operates:

  1. Export App3Service in App3Module.
  2. Import App3Module in App2Module.
  3. Import App2Module in App1Module.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding JavaScript's JSON Path Variables

I've scoured the internet for solutions to a similar issue but haven't been able to find any helpful information yet. My current challenge involves accessing a picture path (in JSON format) based on the material type of the selected element. Her ...

Incorporating geocoding functionality in an asp.net mvc project and looking to efficiently transfer latitude and longitude data from JavaScript to a controller function

UPDATED. Following your suggestions, I implemented the function as shown below: [HttpPost] public ActionResult populate_place(string lati, string longi) { list_placesModels list_place = new list_placesModels(); list_place.Latitude = lati; li ...

Incorporate JSON when adding a new row to the database using Ruby On Rails

Greetings, fellow developers! I am currently working on an application with a backend in Rails. My goal is to create a user from an AJAX request and have the server return a JSON object containing the newly saved user information. Below is my Rails code s ...

I am struggling to capture the user's input and display it on a webpage using HTML and JavaScript. Can you help me identify where I may be going wrong in this process?

Good day! I am fairly new to the programming world and have recently embarked on my first JavaScript project. I've chosen to create a simple budgeting app. However, I'm struggling with displaying user input on the page. Something seems off with ...

When I avoid using a string ref, I encounter the error message "Error: Function components are not allowed to have string refs"

Recently, I created a new component const Projects = () => { const state ={ activeItemID: 1 } const CarouselRef = useRef(null); const NextSlide = () => { CarouselRef.current.style = "opacity: 0"; } return( <Co ...

Tips for making a bookmark for your iframe content

Within this HTML code, there is a list element with the ID "about_ma" and an iframe named "page" that is initially hidden. <div id="navigation"> <ul id="nav"> <li id="about_ma"><a href="index1.php?name=about.php">Ab ...

What is the most effective method to activate OnClientCommand from the server's perspective?

I've found myself in a bit of a dilemma - it seems that solving this issue will require some restructuring of my code. The situation involves a server-side timer running that needs to emulate clicking a tab on a RadTabStrip. On the client side, I hav ...

What is the best way to execute a randomly chosen function in JavaScript?

I need help running a random function, but I'm struggling to get it right. Here's what I have so far: <script> function randomFrom(array) { return array[Math.floor(Math.random() * array.length)]; } function randomchords(){ randomFrom ...

Here's a way to programmatically append the same icon to multiple li elements generated using document.createElement:

I am new to creating a to-do app and need some guidance. When a user enters a task, I successfully create a list item for that task. However, I am unsure how to add a delete icon next to the newly created li element. Can someone please help me out? Below ...

Is there a JavaScript API available for conducting currency calculations?

I'm facing an arithmetic problem that requires handling decimal numbers in JavaScript. Is there an API available for performing comparison, subtraction, and addition of decimals that also supports locale/language-specific formatting? Any suggestions o ...

Steps to create a toggle click event

I've been attempting to create a toggle click event using the code below: HTML <a class="load" data-gallery="123456" style="cursor: pointer;"><h2><p>example</p></h2></a> <div id="123456"> </div> j ...

Prevent clicking on a div using Jquery

Imagine I have a simple click event set up for an HTML div element. When the div is clicked, it should trigger a fadeToggle effect. Inside that div, there is another nested div with its own click event. Upon clicking this inner div, it is supposed to do s ...

The response you have received is delayed by one response

I seem to be facing an issue with my Node.js server where the response I receive is always delayed by one. The response I expect to get at the time of pressing the upload button is always received one step later. After starting the Node server, the initia ...

Activate the text area message by clicking on the href link

I am currently working on customizing the intercom plugin for a WordPress site. My goal is to have a message triggered when a user clicks on a hyperlink, essentially simulating the enter key press in a textarea. Here is the code snippet that I am using: ...

Once an ng-repeat is completed, I must extract and retrieve the 'id' of a specific element

Is it possible to retrieve the 'id' of the comment I'm replying to and save it for an Ajax call? I can easily access other data with ng-model, but using value="{{this.id}}" in a hidden input doesn't seem to work like in JQuery. <scr ...

Is it possible to have the soft keyboard automatically appear when the page loads?

On an HTML5 website, I have an input element and I want the soft keyboard to automatically appear and focus on that input element. I attempted to use the 'autofocus' attribute on the 'input' element, but this only focused on the element ...

Update the text on the form submit button after it has been submitted

Is there a way to change the text on a submit button after it has been clicked? I have a form with a button and I want to switch the text from "click" to "Next" once the form has been submitted. <form> <div class="form-grou ...

Clicking on an element in React Material UI Autocomplete will bring it

I'm currently working with a material-ui autocomplete element <Autocomplete id="combo-box-demo" autoHighlight openOnFocus autoComplete options={this.state.products} getOptionLabel={option => option.productName} style={{ width: 300 ...

Issue with .html causing .hover to malfunction

Attempting a basic image rollover using jQuery, I've encountered an issue with the code below: HTML: <div class="secondcircle" id="circleone"> <p> <img src="/../ex/img/group1.png"> </p> </div> JS: $("# ...

Arrange a collection of words in alphabetical order based on word importance

Given the array below [ { name: '4K UHD', commentator: 'Ali' }, { name: 'English 1 HD', commentator: 'Ahmed' }, { name: 'English 3 HD', commentator: 'Ahmed' }, { name: 'Premium 1 HD&a ...