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
.
提前致谢!