该怎么做呢?
在角1.x中是$watch()方法,但它不在角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.发布于 2018-06-19 13:51:05
我想我找到了解决办法。它是ES6 代理对象。
Proxy是一个特殊的对象,其意思是拦截对另一个对象的调用,并在必要时修改它们并执行其他操作。
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');

发布于 2018-06-19 14:03:46
此外,我还找到了一个使用来自BehaviorSubject的RxJS的解决方案。
// 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 Proxy或RxJS BehaviorSubject进行一些操作更好吗?
https://stackoverflow.com/questions/50915872
复制相似问题