首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Nest无法解决UserService的依赖关系

Nest无法解决UserService的依赖关系
EN

Stack Overflow用户
提问于 2019-11-11 17:51:51
回答 2查看 8K关注 0票数 3

我犯了这个错误

代码语言:javascript
运行
复制
Nest can't resolve dependencies of the UserService (?, SettingsService). Please make sure that the argument UserModel at index [0] is available in the AuthModule context.

    Potential solutions:
    - If UserModel is a provider, is it part of the current AuthModule?
    - If UserModel is exported from a separate @Module, is that module imported within AuthModule?
      @Module({
        imports: [ /* the Module containing UserModel */ ]
      })

auth.module.ts

代码语言:javascript
运行
复制
@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secretOrPrivateKey: config.auth.secret,
      signOptions: {
        expiresIn: config.auth.expiresIn,
      },
    }),
    UserModule,
    SettingsModule,
  ],
  controllers: [AuthController],
  providers: [
    AuthService,
    JwtStrategy,
    LocalStrategy,
    UserService,
    SettingsService,
    Logger,
    ... other services,
  ],
  exports: [PassportModule, AuthService],
})
export class AuthModule {}

user.module.ts

代码语言:javascript
运行
复制
@Module({
  imports: [
    MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
    SettingsModule,
  ],
  controllers: [UserController],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}

app.module.ts

代码语言:javascript
运行
复制
@Module({
  imports: [
    AuthModule,
    UserModule,
    SettingsModule,
    MongooseModule.forRoot(config.db.url),
    WinstonModule.forRoot({
      level: config.logger.debug.level,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

user.service.ts

代码语言:javascript
运行
复制
@Injectable()
export class UserService {
  constructor(@InjectModel('User') private readonly userModel: Model<User>,
              private readonly settingsService: SettingsService) {}

  public async create(user: any): Promise<UserDto> {
    ...
  }

我什么都试过了,但找不到问题,一切似乎都是正确的,我甚至检查了每一个谷歌页面的结果,试图找到它,但我被卡住了。这个错误告诉我,我需要将UserModel导入到AuthModule中,但是它已经存在了,我尝试删除每个用户模型,或者AuthModule,并将它们混合到所有的东西中,但它仍然不起作用,我知道我必须将UserService导出到AuthModule,但是找不到正确的方法。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-12 09:23:08

您将在您的UserService中提供AuthModule。但是,它应该只存在于您的UserModule中。在AuthModule中,UserModel是未知的。

票数 4
EN

Stack Overflow用户

发布于 2022-09-14 16:11:44

再次检查您的模块导入:

代码语言:javascript
运行
复制
@Module({
  imports: [
    MongooseModule.forFeature([
       { name: 'User', schema: UserSchema }
    ]),
    ...
  ],
  ...
})
export class XModule {}

找出愚蠢的错误!因为即使相互传递模式和模式名称,也不会出现类型错误!如果你犯了这么多可能的错误,一般的Nest can't resolve dependencies将是你所得到的全部.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58806309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档