How to inject interface in module of nestjs app

删除回忆录丶 提交于 2021-01-29 20:14:54

问题


Here is the screenshot of error:

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.

Here is the code of app module:

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

Here is the code of Usersinterface:

import * as mongoose from 'mongoose'

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

Here is the code of UsersModule:

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

Here is the code of UsersService:

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

回答1:


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.

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.



来源:https://stackoverflow.com/questions/61387283/how-to-inject-interface-in-module-of-nestjs-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!