Injecting separate configuration for a generic Angular service

50 Views Asked by At

I have a generic data service which has its configuration injected as per below:

export default class GenericDataService<T> implements IGenericDataService<T> {
  constructor(private readonly httpClient: HttpClient,
  private readonly config: GenericDataServiceConfig
) { }

GenericDataServiceConfig has things like baseUrl, endpoint etc.

This data service is injected into a shared lookup component like so:

export class GenericLookUpComponent<T> implements OnInit {
  constructor(private readonly dataService: GenericDataService<T>) {}
...
}

The service is also injected into a component onto which the GenericLookupComponent is placed:

export class LookupDemoComponent implements OnInit {
  constructor(private readonly nominalService: GenericDataService<Nominal>) { }
...
}

So I have two instances of the GenericDataService but both need different configurations, one on the shared lookup component and one on the demo component

I know I can inject the configuration in the component providers like so:

@Component({
  selector: 'app-lookup-demo',
  templateUrl: './lookup-demo.component.html',
  providers: [
    GenericDataService,
    { provide: GenericDataServiceConfig, useValue: nominalConfig }
  ]
})

...but both instances of the service are picking up the same configuration.

How can I specify different configuration for the different instances of the service?

0

There are 0 best solutions below