首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角度6:如何跟踪组件中变量的变化?

角度6:如何跟踪组件中变量的变化?
EN

Stack Overflow用户
提问于 2018-06-18 18:59:06
回答 2查看 2.8K关注 0票数 1
  1. 页面组件中有一个数组;
  2. 在组件中的几个不同位置,一个新元素被添加到这个数组中(在createMessage()方法中和在getIncomingMessagesStream()的订阅服务器中);
  3. 每次向数组中添加一个新元素时,我都需要一次执行几个操作(向下滚动页面和一些操作);
  4. 我不想在多个地方执行额外的操作,而是希望在组件中的某个点执行此操作,当一个新值添加到我的数组中时。

该怎么做呢?

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

代码语言:javascript
复制
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.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-19 13:51:05

我想我找到了解决办法。它是ES6 代理对象。

Proxy是一个特殊的对象,其意思是拦截对另一个对象的调用,并在必要时修改它们并执行其他操作。

代码语言:javascript
复制
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');

Objects/Proxy

票数 0
EN

Stack Overflow用户

发布于 2018-06-19 14:03:46

此外,我还找到了一个使用来自BehaviorSubject的RxJS的解决方案。

代码语言:javascript
复制
// 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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50915872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档