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

后端 未结 3 849
无人及你
无人及你 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: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) => {
                    console.log(record.key + ': ' +  record.previousValue + '=>' + record.currentValue) });
    
            change.forEachRemovedItem(                
                    (record: KeyValueChangeRecord) => {
                        console.log(record.key + ': ' +  record.previousValue + '=>' + record.currentValue) });
    
            change.forEachAddedItem((record: KeyValueChangeRecord) => {
                    console.log(record.key + ': ' +  record.previousValue + '=>' + record.currentValue) });
        }
    }
    

提交回复
热议问题