我正在尝试在使用 jQuery 的现有项目中使用 RxJS。每次单击该按钮时,都会将一个新值推送给用户
。如何查看 of(users).subscribe(...)
中对 users
的更改?
<button class="hello">Hello</button>
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>
const { of } = rxjs
let users = [
{ a: "b" }
]
of(users).subscribe(data => {
console.log(data)
})
jQuery(document).on('click', '.hello', function () {
users.push({ c: 'd' })
})
最佳答案
使用 RxJS scan
运算符,您可以将流转换为不同的形式,类似于 JavaScript 的 native .reduce()
方法的工作原理。在此示例中,每当您想要“推送”到 users 数组时,您只需在 newUser 主题上发出另一个用户即可。
// Create a new subject
const newUser = new Subject();
// Use scan to add new users into array of users
const users = newUser.pipe(scan((acc, user) => [ ...acc, user ], []));
// Subscribe to the list of users and log
users.subscribe(data => console.log(data));
// Add new user to array on document click
jQuery(document).on('click', '.hello', () => users.next({ c: 'd' }));
关于javascript - 订阅数组更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53938124/