@Module({ providers: [AService] exports: [AService] }) export class AModule { } @Module({ imports: [AModule], providers: [BService] exports: [BService] }) export class BModule { }
My code
@Module({ imports: [BModule], providers: [CService] }) export class CModule { }
How can I override/replace the AService
provider from my code? (without third party library patching)
Following on from my comment, this is how you would go about making a dynamic module with a dynamic provider
export interface ProviderInterface {
handle(): void;
}
@Injectable()
class SomeHandlingProvider {
constructor(@Inject('MY_DYNAMIC_PROVIDER') private readonly dynamicProvider: ProviderInterface) {}
handle(): void {
this.dynamicProvider.handle();
}
}
@Module({})
export class AModule {
public static forRoot(provider: ProviderInstance): DynamicModule {
return {
module: AModule,
providers: [
{
provide: 'MY_DYNAMIC_PROVIDER',
useClass: provider,
},
SomeHandlingProvider,
],
};
}
}
Then you can use like this
class GenericDynamicProviderExample implements ProviderInterface {
handle(): void {
console.log('hello');
}
}
@Module({
imports: [
AModule.forRoot(GenericDynamicProviderExample),
],
})
export class BModule {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.