gpt4 book ai didi

javascript - 从 rxjs 存储中的状态获取最新的 2 个值

转载 作者:行者123 更新时间:2023-11-29 20:35:02 25 4
gpt4 key购买 nike

我需要跟踪商店最新id的变化,所以我需要获取变化前后的值。

 this.store.select(currentSearchSelector).subscribe(search => {
this.currentSearchId = search.id;
console.log('current ' + this.currentSearchId);
// I need to detect the change on this id in the store
});

什么是关注最新的变化而不丢失以前的变化?

例如:如果 currentSearchID = 21 然后更改为 22 我需要检测此更改。在我的订阅中,监听器将只持续获取最新的更改。

最佳答案

感谢您的提问!

我想你可以使用 bufferCount值为 2 的运算符。

它将创建一个可观察对象,该对象将仅在缓冲区已满时才发出值,并将值作为数组发出。要查找更多信息,您可以查看 official documentation .

附言在您的情况下,缓冲区的大小应为 2。

this.store.select(currentSearchSelector)
.pipe(bufferCount(2))
.subscribe(([previousSearch, currentSearch]) => {
this.currentSearchId = currentSearch.id;
console.log('current ' + this.currentSearchId);
console.log('previous ' + previousSearch.id);
});

此外,还有一个使用 bufferCount 运算符 StackBlitz 的示例

更新

pairwise operator是 bufferCount 的一个更具体的版本,它只是一起发出最后两项,在这里可能更合适。

无论您选择哪个,您可能还需要将其与 filter operator 结合使用检查搜索 ID 的变化。

关于javascript - 从 rxjs 存储中的状态获取最新的 2 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56968871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com