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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *