I know how to inject a service into a component (via @Component), but how can I use DI to pass around services outside of components?
In other words, I don\'t want t
bootstrap()
if you only one once instance of each service (singletons).@Injectable()
decorator on any service that depends on another.boot.ts
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
import {MyFirstSvc} from '../services/MyFirstSvc';
import {MySecondSvc} from '../services/MySecondSvc';
bootstrap(AppComponent, [MyFirstSvc, MySecondSvc]);
MySecondSvc.ts
import {Injectable} from 'angular2/core';
import {MyFirstSvc} from '../services/MyFirstSvc';
@Injectable()
export class MySecondSvc {
constructor(private _firstSvc:MyFirstSvc) {}
getValue() {
return this._firstSvc.value;
}
}
See Plunker for other files.
What's a bit odd about Service DI is that it still depends on components. E.g., MySecondSvc
is created when a component requests it, and depending on where MyFirstSvc
was "provided" in the component tree, that can affect which MyFirstSvc
instance is injected into MySecondSvc
. This is discussed more here: Can you only inject services into services through bootstrap?