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