我正处于Angular 2的学习模式。我正在以角度实现单件服务,只是为了知道它是如何工作的。 这是我的服务类
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
constructor() {
console.log("new instance");
}
dataValue: string = "i am singleton";
}
这是我的两个组件,我首先使用此服务
import { Component } from '@angular/core';
import { DataService } from './dataservice';
@Component({
selector: 'first',
template: `
<div>
Your Input : <input type = "text" [(ngModel)] = "ChangeByFirstComponent">
You Entered : {{ChangeByFirstComponent}}
</div>
`
})
export class FirstComponent {
constructor(private _dataService: DataService) { }
ChangeByFirstComponent: string;
get DataValue(): string {
return this._dataService.dataValue;
}
set DataValue(ChangeByFirstComponent)
{
this._dataService.dataValue = this.ChangeByFirstComponent;
}
}
second one
import { Component } from '@angular/core';
import { DataService } from './dataservice';
@Component({
selector: 'second',
template: `
<div>
Your Input : <input type = "text" [(ngModel)] = "ChangeBySecondComponent">
You Entered : {{ChangeBySecondComponent}}
</div> `
})
export class SecondComponent {
constructor(private _dataService: DataService) { }
ChangeBySecondComponent: string;
get DataValue(): string {
return this._dataService.dataValue;
}
set DataValue(ChangeByFirstComponent) {
this._dataService.dataValue = this.ChangeBySecondComponent;
}
}
我在单个实例的根模块中提供了提供程序,因此我正在检查它抛出开发人员工具。 我正在实现,如果用户更改firstcomponent的值,所以它应该在secondcomponent上更改为(这是singleton提供给我们的,使数据共享容易)。我没有得到我的输出。有什么问题?