typescript - nestjs and typeorm - failing to setup the dependency injection
问题描述
I am trying to use nestjs
and typeorm
to write a basic CRUD application working but I am failing to get the dependency injection working. I am trying to put the code setups the database into separate modules and import it.
This is the error I am getting:
[ExceptionHandler] Nest can't resolve dependencies of the QuestionController (?). Please make sure that the argument at index [0] is available in the current context. +14ms 4: v8::internal::MaybeHandle v8::internal::(anonymous namespace)::HandleApiCallHelper(v8::internal::Isolate*, v8::internal::Handle, v8::internal::Handle, v8::internal::Handle, v8::internal::Handle, v8::internal::BuiltinArguments) [/usr/local/bin/node]
This is the basic code structure:
database.module.ts
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'sqlite',
database: 'database.sqlite',
}),
],
})
export class DatabaseModule {
}
question.module.ts
:
@Module({
imports: [
DatabaseModule,
TypeOrmModule.forFeature([Question]),
],
providers: [QuestionDal, QuestionLogic],
})
export class QuestionModule {
}
app.module.ts
@Module({
imports: [QuestionModule],
controllers: [QuestionController],
providers: [],
})
export class AppModule {
}
question.dal.ts
@Injectable()
export class QuestionDal {
constructor(@InjectRepository(Question) private questionRepo: Repository<Question>) { }
}
question.logic.ts
@Injectable()
export class QuestionLogic {
constructor(private questionDal: QuestionDal) { }
}
question.controller.ts
@Controller()
export class QuestionController {
constructor(private readonly appService: QuestionLogic) { }
}
I appreciate any help or hint
解决方案
You have to export the QuestionLogic
provider inside the QuestionModule
.
You will be able to inject it in others modules importing the QuestionModule
.
@Module({
imports: [
DatabaseModule,
TypeOrmModule.forFeature([Question]),
],
providers: [QuestionDal, QuestionLogic],
exports: [QuestionLogic]
})
export class QuestionModule {
}
推荐阅读
- python - 张量流无法导入
- python - 传递给参数“shape”的值的数据类型 float32 不在允许值列表中:int32、int64
- amazon-web-services - AWS S3 超出限制 - 如何更改层类型?
- node.js - 使用Nodejs将JSON对象存储在MySql2的JSON列中
- entity-framework - 实体框架核心迁移
- java - 使用@OneToMany 或@ManyToMany 定位未映射的类(多数据库连接)
- javascript - $filter() 如何在 angularjs 内部工作?
- android - CardView 默认高程值
- flutter - 错误:在初始化程序中只能访问静态成员
- javascript - 反应 onClick 多个处理函数问题