StateService类:
@Injectable () class StateService { public log : string; static count : number = 0; constructor () { this.log = ''; StateService.count++; this.writeToLog ('CREATED '+StateService.count+' at ' + new Date().toString()); } public writeToLog (text : string) : void { this.log += text + '\n'; } }
零件 :
@Component ({ selector : 'Sub-Component',template : `<hr> This is the Sub-Component ! <BR> StateService Log : <pre>{{ _stateService.log }}</pre> <button (click)="WriteToLog ()">Write to log</button> `,providers : [StateService] }) export class SubComponent { constructor (private _stateService : StateService) { } public WriteToLog () : void { this._stateService.writeToLog ('From Sub-Component - This is '+new Date().toString()); } }
除了服务创建一次,当每个组件调用WriteToLog方法时,输出在每个组件中是相同的,但不是。
输出示例:
Instance 1 – Created at Thu Jan 21 2016 11:43:51
From App-Component – This is Thu Jan 21 2016 11:43:54
From App-Component – This is Thu Jan 21 2016 11:43:55
子组件可以输出:
Instance 2 – Created at Thu Jan 21 2016 11:43:51
From Sub-Component – This is Thu Jan 21 2016 11:43:57
From Sub-Component – This is Thu Jan 21 2016 11:43:58
所以看起来服务的2个实例被创建(实例1的实例2)
我只想要一个实例;),当我在日志中追加字符串时,这必须出现在两个组件中。
感谢您的帮助
@NgModule({ providers: [...],...
(由于延迟加载的模块引入自己的范围,因此不会加载的模块)
@Component ({ selector : 'Sub-Component',// providers : [StateService] <== remove })
角度≤2.0.0-RC.5
如果将其添加到组件上,则为每个组件实例获取一个新的服务实例。而是添加到
bootstrap(AppComponent,[StateService]);
您可以通过将其添加到单个组件来进行更细致的控制,然后此组件和所有子项都会注入相同的实例,但是其他应用程序可以与由bootstrap()创建的实例配合使用。这是角度DI中的“等级”。
也可以看看
– http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html
– http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html