@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)
The @Injectable() decorator marks the CatsService class as a provider. cats.service.ts. import { Injectable } from '@nestjs/common'; import { Cat } from './interfaces/cat.interface'; @Injectable() export class CatsService { private readonly cats: Cat[] = []; findAll(): Cat[] { return this.
In fact, what our register() method will return is a DynamicModule . A dynamic module is nothing more than a module created at run-time, with the same exact properties as a static module, plus one additional property called module .
A DTO is an object that defines how the data will be sent over the network. We could determine the DTO schema by using TypeScript interfaces, or by simple classes. Interestingly, we recommend using classes here.
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 {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With