如何在nestjs应用程序的模块中注入接口 [英] How to inject interface in module of nestjs app

查看:31
本文介绍了如何在nestjs应用程序的模块中注入接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误截图如下:

我得到了很多关于这个问题的答案,但我没有得到任何正确的解决方案.当我从下面的代码中删除 UsersModule 时,我在邮递员中找不到 404 的错误.但是当我在下面的代码中编写 UsersModule 时,我得到了屏幕截图中提到的错误.

I got many answers for this problem but i didn't get any exact proper solution.When i remove UsersModule from below code then i got error of 404 not found in postman.But when i write UsersModule in below code then i got error which is mentioned in screenshot.

这是应用模块的代码:

@Module({
  imports: [UsersModule,MongooseModule.forRoot("mongodb://localhost:27017/jwt",{ useNewUrlParser: true })],
  controllers: [AppController],
  providers: [AppService]
})
export class AppModule {}

这是用户界面的代码:

import * as mongoose from 'mongoose'

export interface Usersinterface  extends mongoose.Document {
    readonly username: string;
    readonly password: string;
}

这是用户模块的代码:

@Module({
  imports:[UsersModule],
  providers: [UsersService],
  controllers: [UsersController],
  exports:[UsersService]
})
export class UsersModule {}

这是UsersService的代码:

Here is the code of UsersService:

@Injectable()
export class UsersService {
    private hashLength = 16;
    constructor(@InjectModel('Usersinterface') private readonly userModel:Model<Usersinterface>) {}

推荐答案

接口只存在于编译期,用于类型检查,因此不能用于注入令牌.如果您希望将接口"用于注入令牌,您可以将其与 @Inject() 和使用自定义提供程序的实际注入令牌结合使用,或使用类接口(使用没有比实际的面向对象类更能用作形状的逻辑了.

Interfaces only exist during compile time, and are used for type checking, and as such, cannot be used for Injection Tokens. If you are looking to use an "interface" for an injection token, you can combine it with @Inject() and an actual injection token using custom providers, or using a Class Interface (making a class with no logic to be used more as a shape than an actual Object Oriented class.

话虽如此,您似乎正在尝试将 Mongoose 模型注入您的 UsersService.为此,您需要确保当前模块的 imports 数组中有 MongooseModule.forFeature([schemaObject]).GitHub 上的示例 展示了一个很好的示例.

That being said, it looks like you are trying to inject a Mongoose Model into your UsersService. To do this, you need to make sure you have MongooseModule.forFeature([schemaObject]) in your current module's imports array. The sample on GitHub shows a pretty good example.

这篇关于如何在nestjs应用程序的模块中注入接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆