For example:
@NgModule ({
providers: [
{ provide: MyService,
useFactory: (optionalDep) => new MyService(optionalDep)
deps: [SOME_DEP]
}
})
class MyModule {}
Can useFactory have optional dependencies?
Optional dependencies are used when it's not possible (for whatever reason) to split a project into sub-modules. The idea is that some of the dependencies are only used for certain features in the project and will not be needed if that feature isn't used.
Class Provider: useClassThe useClass expects us to provide a type. The Injector creates a new instance from the type and injects it. It is similar to calling the new operator and returning instance. If the type requires any constructor parameters, the injector will resolve that also.
Factory providers: useFactory link The useFactory provider key lets you create a dependency object by calling a factory function, as in the following example. The injector provides the dependency value by invoking a factory function, that you provide as the value of the useFactory key.
Angular has an @Optional decorator, which when applied to a constructor argument instructs the Angular injector to inject null if the dependency is not found.
According to official doc, you can do the following:
const Location = new InjectionToken('location');
const Hash = new InjectionToken('hash');
const injector = Injector.create([{
provide: Hash,
useFactory: (location: string) => `Hash for: ${location}`,
// use a nested array to define metadata for dependencies.
deps: [[new Optional(), Location]]
}]);
expect(injector.get(Hash)).toEqual('Hash for: null');
See https://angular.io/api/core/FactoryProvider#example for more
I have found such a workaround:
class OptionalDepHolder {
constructor(@Optional() @Inject(SOME_DEP) public optionalDep) {}
}
@NgModule ({
providers: [
{ provide: MyService,
useFactory: (holder) => new MyService(holder.optionalDep)
deps: [OptionalDepHolder]
}
})
class MyModule {}
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