【发布时间】:2016-07-28 01:04:25
【问题描述】:
Angular1老手在这里,尝试学习angular2。我有一个带有状态服务的组件(下面的MyState),它被注入到自身及其子组件中。我想观察服务状态的变化,然后更新顶级组件中的另一个成员,如下:
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,然后你可以订阅更改。 angular.io/docs/ts/latest/cookbook/component-communication.html
-
感谢@GünterZöchbauer 的领导!后续问题:创建 Observable
作为状态本身的属性是否符合规定?
标签: typescript angular angular2-services angular2-changedetection