Angular service injection hierarchy

31 Views Asked by At

I have a service MyService which needs to be defined in a module ModuleCommon, and used in modules ModuleA and ModuleB. The dependencies of MyService vary between ModuleA and ModuleB.

Example:

export class MyService {
  constructor(@Inject(XInjectionToken) dep: IDependency) { }
}

In ModuleA, IDependency implementation should be a ModuleADependency, whereas in ModuleB it's a ModuleBDependency.

How can I add MyService definition to ModuleCommon and 'defer' the injection of XInjectionToken until it can be provided by the child module?

1

There are 1 best solutions below

0
user6118986 On

The solution was to add MyService to the providers array of ModuleCommon directly, without using the { provide: InjectionToken, useClass: MyService } syntax. That appears to register the service with DI without instantiating it.