Reputation: 5802
I have a class in Angular2 that requires DI, I am using typescript and I try to inject my service in the following way into a normal class. (Not a component, I can inject the service in components without any problem)
constructor(@Inject(SidebarService) sidebarService : SidebarService)
Before I have tried to annotate the class with @Inject
in the hopes that this would make typescript generate the necessary code for DI to work.
In both cases, when I try to construct the object, I will get a message telling me that an argument for the constructor is missing.
for example
this.sidebarHelper = new ItemSidebarHelper();
Will say error TS2346: Supplied parameters do not match any signature of call target.
What would be the correct way to use DI in this case?
Upvotes: 2
Views: 156
Reputation: 2080
Actually, you can inject Angular's injector into your classes
@Component({
selector: 'my-injectors',
template: `
<h2>Other Injections</h2>
<div id="car">{{car.drive()}}</div>
<div id="hero">{{hero.name}}</div>
<div id="rodent">{{rodent}}</div>
`,
providers: [Car, Engine, Tires, heroServiceProvider, Logger]
})
export class InjectorComponent {
car: Car = this.injector.get(Car);
heroService: HeroService = this.injector.get(HeroService);
hero: Hero = this.heroService.getHeroes()[0];
constructor(private injector: Injector) { }
get rodent() {
let rousDontExist = `R.O.U.S.'s? I don't think they exist!`;
return this.injector.get(ROUS, rousDontExist);
}
}
From: https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#explicit-injector
Upvotes: 0
Reputation: 23506
Regarding your comments I edited the answer for usage of a singleton service without dependency resolution:
class SidebarService {
static instance: SidebarService;
static instantiating: Boolean = false;
constructor() {
if (!SidebarService.instantiating) {
throw new Error("Use SidebarService.getInstance()");
}
}
static getInstance(): SidebarService {
if (SidebarService.instance == null) {
SidebarService.instantiating = true;
SidebarService.instance = new SidebarService();
SidebarService.instantiating = false;
}
return SidebarService.instance;
}
}
class ItemSidebarHelper {
private _sidebarService: SidebarService;
constructor() {
this._sidebarService = SidebarService.getInstance();
}
}
var sidebarHelper = new ItemSidebarHelper();
Plunkr for example usage
Upvotes: 1