使用模块中导出的组件

时间:2018-04-10 10:37:00

标签: typescript nestjs

UserService需要UserModule,然后添加到exports

import {Module} from '@nestjs/common'
import {TypeOrmModule} from '@nestjs/typeorm'
import {User} from './user.entity'
import {UserService} from './user.service'

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  components: [UserService],
  controllers: [],
  exports: [UserService]
})
export class UserModule{}

然后我有AuthModule需要使用UserService来执行此操作:

import * as passport from 'passport'
import * as PassportAzureAD from 'passport-azure-ad'
import * as session from 'express-session'
import {
  Module,
  NestModule,
  MiddlewaresConsumer,
  RequestMethod,
} from '@nestjs/common'
import {Logger} from '@nestjs/common'
import {UserModule} from '../user/user.module'

@Module({
  imports: [UserModule],
  components: [],
  controllers: []
})
export class AuthModule implements NestModule{
  public configure(consumer: MiddlewaresConsumer){
      // SNIP
      // How to use `UserService` here
  }
}

如何在此处使用UserServicedocs说:

  

现在每个导入CatsModule的模块(我们需要将CatsModule放入导入数组)都可以访问CatsService,并且将与导入该模块的所有模块共享同一个实例。

但没有举例说明你的意愿。

1 个答案:

答案 0 :(得分:1)

导出的UserService需要在其构造函数中导入AuthModule,如下所示:

@Module({
  imports: [UserModule],
  components: [],
  controllers: []
})
export class AuthModule implements NestModule{
  constructor(
    private readonly userService: UserService
  ) {}

  public configure(consumer: MiddlewaresConsumer){
    this.userService
  }
}

更多关于依赖注入的信息: