英文:
NestJS - Export Custom Factory Provider (useFactory)
问题
我已经在我的一个模块中创建了一个自定义提供程序。
我需要导出该自定义提供程序,以便在其他模块中使用,并且我在这方面遇到了困难。我不知道应该在exports
数组中放什么。
以下是我的自定义提供程序。
@Module({
imports: [TypeOrmModule.forFeature([TypeOrmUser])],
providers: [
UserMapper,
UserService,
{
provide: getRepositoryToken(TypeOrmUser),
inject: [getDataSourceToken()],
useFactory(dataSource: DataSource) {
return dataSource.getRepository(TypeOrmUser).extend(userRepositoryImpl);
},
},
],
exports: [UserService, '在这里放什么以导出自定义用户仓库?'],
})
export class UsersModule {}
感谢您的帮助。
英文:
I have created a custom provider in one of my modules.
I need to export that custom provider to make it available in other modules and I'm having trouble doing so. I do not know what to put in the exports array.
Below is my custom provider.
@Module({
imports: [TypeOrmModule.forFeature([TypeOrmUser])],
providers: [
UserMapper,
UserService,
{
provide: getRepositoryToken(TypeOrmUser),
inject: [getDataSourceToken()],
useFactory(dataSource: DataSource) {
return dataSource.getRepository(TypeOrmUser).extend(userRepositoryImpl);
},
},
],
exports: [UserService, 'what to put here to export custom user repository?'],
})
export class UsersModule {}
Thank you for your help.
答案1
得分: 1
添加到exports
数组的所有内容,只需添加提供者的注入标记。
在这种情况下,那就是getRepositoryToken(TypeOrmUser)
。
英文:
To export a custom provider, all that is needed to be added to the exports
array is the provider's injection token.
In this case, that's getRepositoryToken(TypeOrmUser)
答案2
得分: 1
你可以通过token名称或整个提供者object导出它。在你的情况下,可能会像这样:
exports: [UserService, getRepositoryToken(TypeOrmUser)],
或者:
const customProvider = {
provide: getRepositoryToken(TypeOrmUser),
inject: [getDataSourceToken()],
useFactory(dataSource: DataSource) {
return dataSource.getRepository(TypeOrmUser).extend(userRepositoryImpl);
},
};
@Module({
imports: [TypeOrmModule.forFeature([TypeOrmUser])],
providers: [
UserMapper,
UserService,
customProvider,
],
exports: [UserService, customProvider],
})
英文:
You can export it either with token name, or with the whole provider object. In your case it would be something like this:
exports: [UserService, getRepositoryToken(TypeOrmUser)],
or:
const customProvider = {
provide: getRepositoryToken(TypeOrmUser),
inject: [getDataSourceToken()],
useFactory(dataSource: DataSource) {
return dataSource.getRepository(TypeOrmUser).extend(userRepositoryImpl);
},
};
@Module({
imports: [TypeOrmModule.forFeature([TypeOrmUser])],
providers: [
UserMapper,
UserService,
customProvider,
],
exports: [UserService, customProvider],
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论