Angular1在这里尝试学习angular2。我有一个具有状态服务的组件(下面的MyState
),它被注入到它自己及其子组件中。我想看关于该服务的状态发生变化,然后更新在顶级组件另一名成员,具体如下:在angular2中更改对注入服务属性的检测
import { Component, Input } from '@angular/core';
class Item {
constructor(public name: string) {}
}
class MyState {
selectedItems: Item[] = [];
addItem(item: Item) {
this.selectedItems.push(item);
}
}
// subcomponent
@Component({
selector: '[item]',
template: `
<!-- state changed from subcomponent: -->
<button (click)="state.addItem(model)">
select item {{model.name}}
</button>
`
})
class ItemComponent {
@Input() model: Item;
constructor(private state: MyState){}
}
// main component
@Component({
selector: 'items',
template: `
<h1> Available Items: </h1>
<ul>
<li *ngFor="let item of items" item [model]="item"></li>
</ul>
<h1> Added Items: </h1>
<p>{{ addedItemsString }}</p>
`,
providers: [MyState],
directives: [ItemComponent]
})
class ListComponent {
@Input() items: Item[];
private addedItemsString: string = '';
constructor(private state: MyState) {
// listen for changes to this.state.selectedItems to
// call this.updateAddedItemsString
}
updateAddedItemsString() {
this.addItemsString = this.state.selectedItems.map(i => i.name).join(', ');
}
}
我的问题是:我应该如何实现在ListComponent构造函数中的伪代码?
诚然,addItemsString
成员是人为的,并可以肯定是在模板本身来完成,但对于我的问题的缘故假设updateAddedItemsString
可以做很多,更新的ListComponent
不同的部件更复杂的东西。
在此先感谢!
在您的服务中使用observable,然后您可以订阅更改。 https://angular.io/docs/ts/latest/cookbook/component-communication.html –
感谢领先@GünterZöchbauer!后续问题:创建一个Observable作为国家本身的财产是否可以接受? –
AndyPerlitch