Categories
TypeScript Answers

How to inject Nest.js service from another module with TypeScript?

Spread the love

Sometimes, we want to inject Nest.js service from another module with TypeScript.

In this article, we’ll look at how to inject Nest.js service from another module with TypeScript.

How to inject Nest.js service from another module with TypeScript?

To inject Nest.js service from another module with TypeScript, we’ve to export the module before we can import it.

For instance, we write

@Module({
  controllers: [ItemsController],
  providers: [ItemsService],
  exports: [ItemsService],
})
export class ItemsModule {}

to export the ItemsService with

exports: [ItemsService],

Then in another module file, we write

@Module({
  controllers: [FooController],
  providers: [FooService],
  imports: [ItemsModule],
})
export class FooModule {}

to import the ItemsModule with

imports: [ItemsModule],

Conclusion

To inject Nest.js service from another module with TypeScript, we’ve to export the module before we can import it.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.