0

How to inject multiple service instances into angular components of the same service?

For example - I have dbService in my code and I want to call this dbService instance two times and init both the services with two different values in the constructor. But When I create two instances in component like

constructor( private db1:dbService, private db2:dBservice ){}

It is basically same instance being injected. How to implement such use case in angular 2+ or later.

Roman Skydan
  • 5,478
  • 4
  • 19
  • 39
  • 3
    Possible duplicate of [Angular2 DI - initializing multiple different instances in the same constructor](https://stackoverflow.com/questions/38213995/angular2-di-initializing-multiple-different-instances-in-the-same-constructor) – rrd Jan 25 '18 at 22:11

1 Answers1

2

You can create a method in your service which return you instance of that service. something like this -

public static instance: dbService;
public static getInstance(http: Http): dbService {
    if (!dbService.instance) {
        dbService.instance = new dbService(http);
    }
    return dbService.instance;
}
private constructor(public http: Http) {
}

PRIVATE CONSTRUCTOR TO MAKE SURE THAT IT CAN'T BE CALLED FROM OUTSIDE

Then in your component you can call getInstance() method as many times as you want.

Abhishek Gangwar
  • 2,168
  • 18
  • 26