【问题标题】:How to trigger event when array item value changes数组项值改变时如何触发事件
【发布时间】:2021-06-17 20:10:51
【问题描述】:

我的数组中有对象。 当更改对象的值时,我们说 id。我需要触发一个事件或类似的东西。

这就是我添加对象的方式:

 const entry= new CompletableEntry('models.Address.addressLine2._TITLE');
 this.globalLoadingScreenService.addTask(entry);
 task.updateID(3);

更新 ID 不会触发任何事情,但我有一个函数需要在值更改时触发。该函数检查所有对象是否具有完成状态,如果是,它将删除数组中的所有项目。

我知道实现这一点的一种方法是通过我的服务添加它们,但我需要一种不会通过服务更新任务状态的解决方案。

【问题讨论】:

    标签: angular typescript events triggers


    【解决方案1】:

    您可以创建一个可以订阅的自定义 observable 数组。 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
    })
    
    

    【讨论】:

    • 我使用了您的答案,但方式不同。当状态改变时,创建了一个完成的字段,它是一个 BehaviourSubject,所以当我添加一个新条目时订阅它并且当它改变时我得到一个触发器。如果我将状态用作 BehaviourSubject,它也会起作用。我会修改你的答案并给出并选择它作为正确答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    相关资源
    最近更新 更多