0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
user3659739
  • 434
  • 6
  • 19

1 Answers1

1

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);
  }
}
Clive Ciappara
  • 558
  • 5
  • 11
  • Maybe i don't understand your answer but i don't think it answers my question because in the constructor i can't access to my variable isLocal, only in ngOnInit and i dont want 2 variables for services i just want one – user3659739 Jan 26 '21 at 08:01