ppotera
ppotera

Reputation: 61

serviceFactory as a dependecy (deps: []) in Provider Object - is it possible?

I got provider in app.module defined as follows:

{
                    multi: true,
                    deps: [ServiceA, ServiceB],
                    provide: HTTP_INTERCEPTORS,
                    useClass: HttpResponseInterceptor,
}

And it works fine. Problem is, I need ServiceB to be configurable by factory function and also serviceB is optional but something like this doesn't work:

// Factory function
serviceBFactory = (param) => { // returns instance of my service or null, depends on param }

...
deps: [ ServiceA, { provide: ServiceB, useFactory: serviceBFactory } ]
...

Error I get:

Error: StaticInjectorError(AppModule)[InjectionToken HTTP_INTERCEPTORS -> [object Object]]: 
  StaticInjectorError(Platform: core)[InjectionToken HTTP_INTERCEPTORS -> [object Object]]
NullInjectorError: No provider for [object Object]!

Is there any special syntax for it or it's not possible by design?

Upvotes: 0

Views: 83

Answers (1)

ppotera
ppotera

Reputation: 61

Let me answer to my own question ;-) So I decided to build InjectionToken manually:

export function serviceBFactory() {
    if (APP_CONFIG.serviceBNeeded) {
        return new ServiceB();
    } else {
        return null;
    }
}

const ServiceBToken: InjectionToken<ServiceB> = new InjectionToken<ServiceB>(
  'ServiceB instance or Null', 
  {
    providedIn: 'root',
    factory: serviceBFactory,
  }
);

And then just pass it to deps array...

deps: [ServiceBToken]

I don't know if it's OK or if there is maybe a better way to achieve what I wanted but this solution works at least.

Upvotes: 0

Related Questions