What is the best way to run two different version of same service in same component?

I want to run two instances of the same component but each instance will receive a different version of the service. I need this to provide some kind of backward compatibility of my component with two versions of the same service. One option might be to use an injection token with multi true. But not sure how each component knows which version to run.

Some example would be useful here, probably. Because it’s not very clear what you want to achieve with these service instances.

Without knowing that I would suggest to add some input parameter for the component depending on which the component would choose the service to use. And probably instantiate the service without dependency injection if it’s possible (would be simpler in this case probably), like service1 = new MyService(); service2 = new MyService();

1 Like

@oblogera thanks for the help…!!
The use case is like I have two services of HTTP client. One had some calls to the old version of API and the second service is having API calls to the new version. Now from my component, I need to support both and I don’t know whether the user wants to use the old one or a new one or both of two for different instances of the same component.
So, I am thinking like get the services via injection token with multi true. Now I have both services in the token and via attribute decorator or input prop, I can get the service name, and based on this I can set my active service client.

When you say “two versions of the same service”, that sounds like two different services that implement the same interface. You can inject both services into the component. In the components constructor assign the service to a class property based on a condition e.g.

@Input() shouldUseV1: boolean
private service: IServiceVersion;

constructor(v1: ServiceV1, v2; ServiceV2) {
     this.service = this.shouldUseV1 ? v1 : v2;

Alternatively you could use a conditional provider with useFactory, there’s a good example here Provide different Angular service based on condition at runtime | by Maarten Merken | Agilix | Medium

1 Like

Yes, both services implement a similar interface. But the services are in two different packages(say like package-a-v1, package-a-v2) and I don’t know if the user has installed both packages or a single one. Also with useFactory, it will configure once. But if the user wants to run both versions of services(say like one instance of <app-xyz></app-xyz> with serviceA and another instance of <app-xyz></app-xyz> with serviceB). In this case, I need to get some input/attribute at the component level and check if the given service is available then use it.