本文介绍了Angular2监视对象/数组更改(Angular2 final> = 2.1.1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想观看一个对象/数组,可以通过服务或控制器例程对其进行编辑.我以为Observable可以观看对象/数组.

I'd like to watch an object/array, which ca be edited by a service or by a controllers routine. I thought that an Observable could watch an object/array.

我的实现对项目的更改没有反应:

My implementation doesn't react on changes of the items :

  private data : Observable<Array<any>>;
  private dataObserver: Observer<Array<any>>;
  private sub : Subscription;
  private items: <Array<any>>;

  ngOnInit() {
     this.items = itemService.getItems();
     this.data = new Observable<Array<any>>(observer =>{
        this.dataObserver = observer;
     });
     this.data.subscribe(
        x => console.log('onNext: %s', x),
        e => console.log('onError: %s', e),
        () => console.log('onCompleted')
     );
     this.dataObserver.next(this.items);
  }


private start(){

  //change values of the array in an interval
  let loop = Observable.interval(250)
  let i=0;
  self.sub = loop.subscribe(() => {
      if(self.items[0]){
        self.items[0].id= i;
        if(i<100) i++;
        else i=1;
      }
  })
}

observalbes订阅不会对items数组的更改做出反应.它仅在下一个方法上触发.另一方面,对于简单的观看方法来说,这太麻烦了.

The observalbes subsciption doesn't react on changes of the items array. It only triggers on its next mehtod. On the other hand .. this is too cumbersome for a simple watch method.

angular-2为我们提供了什么来监视变化,就像$ scope.$ watch在angular-1中所做的那样?

What does angular-2 offer us to watch for changes, as $scope.$watch did in angular-1?

推荐答案

Angular2提供了IterableDiffer(数组)和KeyValueDiffer(对象)来获取有关两次检查之间差异的信息.

Angular2 provides IterableDiffer (array) and KeyValueDiffer (object) to get information about differences between two checks.

NgClass是一个很好的例子 https://github.com/angular/angular/blob/14ee75924b6ae770115f7f260d720efa8bfb576a/modules/%40angular/common/src/directives/ng_class.ts#L122

另请参见 https://angular.io/docs/ts/latest/api/#!? query = differ

示例

// inject a differ implementation
constructor(differs: KeyValueDiffers) {
  // store the initial value to compare with
  this.differ = differs.find({}).create(null);
}

@Input() data: any;

ngDoCheck() {
  var changes = this.differ.diff(this.data); // check for changes
  if (changes && this.initialized) {
    // do something if changes were found
  }
}

这篇关于Angular2监视对象/数组更改(Angular2 final&gt; = 2.1.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:27