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

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

问题描述

以下是错误的屏幕截图:

Here is the screenshot of error:

我对这个问题有很多答案,但是我没有任何确切的解决方案.当我从下面的代码中删除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;
}

这是UsersModule的代码:

Here is the code of UsersModule:

@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.

话虽如此,看来您正在尝试将猫鼬模型注入您的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天全站免登陆