怎么做?
在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.
答案 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 Proxy
或RxJS 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');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy