更改对angular2中注入的服务属性的检测

时间:2016-07-26 20:43:40

标签: typescript angular angular2-services angular2-changedetection

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

提前致谢!

1 个答案:

答案 0 :(得分:2)

在您的服务中使用Plunker <Item[]>,并让您的ListComponent订阅对该可观察数组的更改:

class MyState {
  private _selectedItems: Item[] = [];
  private _selectedItemsSource = new BehaviorSubject<Item[]>(this._selectedItems);
  selectedItems$ = this._selectedItemsSource.asObservable();
  addItem(item: Item) {
    this._selectedItems.push(item);
    this._selectedItemsSource.next(this._selectedItems);
  }
}

@Component({
  selector: 'items',
  template: `<h1> Available Items: </h1>
    <ul>
      <li *ngFor="let item of items" item [model]="item"></li>
    </ul>
    <h1> Added Items: </h1>
    <div>{{ addedItemsString }}</div>`,
  providers: [MyState],
  directives: [ItemComponent]
})
class ListComponent {
  @Input() items: Item[];
  private addedItemsString: string = '';
  constructor(private state: MyState) {}
  ngOnInit() {
    this.subscription = this.state.selectedItems$.subscribe(
      items => this.addedItemsString = items.map(i => i.name).join(', '));
  }
  ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this.subscription.unsubscribe();
  }
}

{{3}}

每次调用next()时,我都会发出整个数组。这可确保以后订阅BehaviorSubject的任何其他组件都将获得完整列表。如果您没有这个要求,那么在调用addItem()时只能发出新值。