我创建了 AngularJS 2 服务并在 2 个不同的组件中使用它:App-Component & Sub-Component。我的服务的每个输出属性“日志”(一个字符串)。
状态服务类:
@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());
}
}
代码的实时示例here
我除了该服务创建一次并且当每个组件调用 WriteToLog 方法时,每个组件的输出都是相同的,但事实并非如此。
输出示例:
App-Component 可以输出这个:
实例 1 - 创建于 2016 年 1 月 21 日星期四 11:43:51
来自 App-Component - 这是 2016 年 1 月 21 日星期四 11:43:54
来自 App-Component - 这是 2016 年 1 月 21 日星期四 11:43:55
子组件可以输出这个:
实例 2 - 创建于 2016 年 1 月 21 日星期四 11:43:51
来自子组件 - 这是 2016 年 1 月 21 日星期四 11:43:57
来自子组件 - 这是 2016 年 1 月 21 日星期四 11:43:58
因此,似乎创建了 2 个服务实例(实例 1 + 实例 2)
我只想要一个实例;)当我在日志中附加字符串时,它必须出现在两个组件中。
谢谢您的帮助