1

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 Answer 1

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);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.