Angular 6:如何跟踪组件中变量的变化?

时间:2018-06-18 18:59:07

标签: angular

  1. 页面组件中有一个数组;
  2. 在组件中的几个不同位置,将一个新元素添加到此数组中(在createMessage()方法中和getIncomingMessagesStream()的订阅者内部);
  3. 每次将新元素添加到数组中时,我需要一次执行多个操作(向下滚动页面和一些操作);
  4. 我想在多个位置执行其他操作,而不是在组件内部的某个位置执行此操作,此时将新值添加到我的阵列中。
  5. 怎么做?

    在Angular 1.x中是$ watch()方法,但它不在Angular 2 +中。

    I push a new message to messages array in several places:
    - this.messageService.getIncomingMessagesStream().subscribe(...there...)
    - createMessage() {...there...}
    
    After I push a new message I need to do the same several actions:
    - scroll window to bottom 
    - etc...
    
    Now I have to copy-paste the same actions in every place where I push a new message in messages array.
    
    But I don't want to copy-paste this actions,
    I want to perform them after I push a new element to messages array,
    perform then automatically, from one point in code, without copy-paste,
    I don't want to duplicate this actions.
    

2 个答案:

答案 0 :(得分:1)

我还找到了使用RxJS的BehaviorSubject的解决方案。

// page.component.ts

private appData = new BehaviorSubject<any[]>([]);

constructor() {
    this.appData.subscribe((data) => {
        console.log('New data', data);
    });
}

public addSomethingToAppData(something) {
    this.appData.next([...this.appData.getValue(), something]);
}

http://reactivex.io/rxjs/manual/overview.html#behaviorsubject

在将新元素推入数组后,您认为使用ES6 ProxyRxJS BehaviorSubject进行什么操作更好?

答案 1 :(得分:0)

我想我找到了解决方案。这是ES6 代理对象。

代理是一个特殊的对象,其含义是拦截对另一个对象的调用,并在必要时对其进行修改并执行其他操作。

let my_arr = [];
// Proxy(target, handler)
let arr_proxy = new Proxy(my_arr, {
    get(target, prop) {
        console.log(`\n Getting ${prop}`);
    console.log(`Perform needed actions after getting ${prop}`);
        return target[prop];
    },

    set(target, prop, value) {
        console.log(`\n Setting ${prop} ${value}`);
    console.log(`Perform needed actions after setting ${prop} ${value}`);
        target[prop] = value;
        return true;
    }
});

arr_proxy.push('new message text');

enter image description here

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy