I'm facing a dilemma with Angular2 DI. Let's say I have a TestService
and I need to use 2 distinct instances of this service in one component. However, when I add the provider to the component and include both instances in the constructor, I end up getting the same service instance for both. Here is an example:
TestService
import {Injectable} from "@angular/core";
@Injectable()
export class TestService {
public id: number = Math.random();
public toString(): string {
return "Id: " + this.id;
}
}
Test component
import {Component, Input, OnInit} from "@angular/core";
import {TestService} from "../../services/test.service";
@Component({
providers: [TestService]
})
export class TestComponent implements OnInit {
constructor(private _testService1: TestService, private _testService2: TestService) { };
ngOnInit() {
console.log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", this._testService1.toString());
console.log("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", this._testService2.toString());
}
}
Result displayed in console
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Id: 0.24242492129168425
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB Id: 0.24242492129168425
I'm seeking advice on whether there's a way to leverage Angular2's DI to inject multiple unique instances of a service within the same component or if it's better to forego DI in this scenario and manually create the instances using a custom constructor.
Thank you in advance