Angular2 watch object/array changes (Angular2 final >= 2.1.1)

后端 未结 3 821
无人及你
无人及你 2021-01-04 19:57

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 implem

相关标签:
3条回答
  • 2021-01-04 20:38

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

    NgClass is a good example https://github.com/angular/angular/blob/14ee75924b6ae770115f7f260d720efa8bfb576a/modules/%40angular/common/src/directives/ng_class.ts#L122

    See also https://angular.io/docs/ts/latest/api/#!?query=differ

    An example

    // 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
      }
    }
    
    0 讨论(0)
  • 2021-01-04 20:42

    Thanks for your example Gunter.

    I choose a quick solution based on your response.

    I replace the OnInit handle by a DoCheck implementation. Now if value change in my service external called Language the view is updated.

    In my case example :

    import { Component, DoCheck } from "@angular/core";
    export class LangListUserComponent implements DoCheck {
    
      constructor(private _languageService: LanguageService)
      {}
    
      ngDoCheck() {
        /** Get available lang */
        this.oLanguages = this._languageService.getLanguageList();
        this.setCurrentLang(this.oLanguages);
      };
    }
    
    0 讨论(0)
  • 2021-01-04 20:43

    In the import section:

    import { DoCheck, KeyValueDiffers, KeyValueChangeRecord } from '@angular/core';
    

    Adding the 'KeyValueDiffers' injector:

    private _differ: any;    
    
    constructor(private _differs: KeyValueDiffers) {
        this._differ = _differs.find({}).create();
    }
    

    Finally track changes:

    ngDoCheck() {
        const change = this._differ.diff(this.Your_Object_To_Track);
        if (change) {
            change.forEachChangedItem(
                (record: KeyValueChangeRecord<any, any>) => {
                    console.log(record.key + ': ' +  record.previousValue + '=>' + record.currentValue) });
    
            change.forEachRemovedItem(                
                    (record: KeyValueChangeRecord<any, any>) => {
                        console.log(record.key + ': ' +  record.previousValue + '=>' + record.currentValue) });
    
            change.forEachAddedItem((record: KeyValueChangeRecord<any, any>) => {
                    console.log(record.key + ': ' +  record.previousValue + '=>' + record.currentValue) });
        }
    }
    
    0 讨论(0)
提交回复
热议问题