Angular 11: Is it possible to inject service by condition from an input

1.5k views Asked by At

I have a really big component which works with a service for loading datas and instead of re-writing a similar component for working with a new service, I wrote a service with all the same functions that the first one and I try to dynamically change the injection of the service in the constructor of the component using an input.

So I will have :

@Input() isLocal= false;

private service: Service1|Service2;

constructor(private injector: Injector) {
  if (this.isLocal) {
    this.service = injector.get(Service1);
  } else {
    this.service = injector.get(Service2);
  }
}

My problem is that I can't access my input in the constructor and I can't init my service in ngOnInit. How can I achieve this?

1

There are 1 answers

1
Clive Ciappara On

It would be best if you implement a Factory pattern as is described here:

angular.service vs angular.factory

But for this you can use the Injector class from Angular core:

import { Injector } from '@angular/core'  
...

@Input() isLocal= false;
...

constructor(private injector: Injector){ 

  if(this.isLocal) {
    this.oneService = <OneService>this.injector.get(Service1);
  } else {
    this.twoService = <TwoService>this.injector.get(Service2);
  }
}