如何在数组项值更改时触发事件
How to trigger event when array item value changes
我的数组中有对象。
当更改对象的值时,假设是 id。我需要触发事件或类似事件。
这是我添加对象的方式:
const entry= new CompletableEntry('models.Address.addressLine2._TITLE');
this.globalLoadingScreenService.addTask(entry);
task.updateID(3);
更新 ID 不会触发任何内容,但我有一个函数需要在值更改时触发。该函数检查是否所有对象都具有完成状态,如果是,它将删除数组中的所有项目。
我知道一种方法是通过我的服务添加它们,但我需要一种不会通过服务更新任务状态的解决方案。
您可以创建一个您可以订阅的自定义可观察数组。 This 可能会有帮助。
我想到的是你可以创建一个 BehaviourSubject
并订阅它。
import { BehaviorSubject } from 'rxjs';
arrayChanged = new BehaviourSubject(false);
//The function where actually the array is updating
fun update() {
...
this.arrayChanged.next(!this.arrayChanged.value);
}
// Then to listen to the array changes.
this.arrayChanged.subscribe( value => {
//The function you want to run goes here.
// this block runs everytime there is some change in the behaviour subject
})
我的数组中有对象。 当更改对象的值时,假设是 id。我需要触发事件或类似事件。
这是我添加对象的方式:
const entry= new CompletableEntry('models.Address.addressLine2._TITLE');
this.globalLoadingScreenService.addTask(entry);
task.updateID(3);
更新 ID 不会触发任何内容,但我有一个函数需要在值更改时触发。该函数检查是否所有对象都具有完成状态,如果是,它将删除数组中的所有项目。
我知道一种方法是通过我的服务添加它们,但我需要一种不会通过服务更新任务状态的解决方案。
您可以创建一个您可以订阅的自定义可观察数组。 This 可能会有帮助。
我想到的是你可以创建一个 BehaviourSubject
并订阅它。
import { BehaviorSubject } from 'rxjs';
arrayChanged = new BehaviourSubject(false);
//The function where actually the array is updating
fun update() {
...
this.arrayChanged.next(!this.arrayChanged.value);
}
// Then to listen to the array changes.
this.arrayChanged.subscribe( value => {
//The function you want to run goes here.
// this block runs everytime there is some change in the behaviour subject
})