首页 > 解决方案 > 使用 Observable 过滤器过滤对象数组

问题描述

我正在努力寻找使用 RxJS 6 过滤对象数组的正确方法。

这是场景。我有users: User[],filter: FormControl和另一个数组filteredUsers: User[]. 我想做的是根据filter. 我能够弄清楚这一点的唯一方法是使用tap,虽然这有效,但它似乎不是正确的方法......加上整个列表被“过滤掉”,直到过滤器控件有它第一个值变化。

this.filter.valueChanges.pipe(
  tap((term) => {
    this.filteredUsers = this.users.filter(u => u.name.indexOf(term) != -1)
  })).subscribe()

任何帮助将不胜感激。

标签: angularrxjs6

解决方案


你是对的,点击不是“正确”的方式......正确的方式是在订阅中进行......

this.filter.valueChanges.pipe(startWith('')).subscribe(
  (term) => {
    this.filteredUsers = (term) ? this.users.filter(u => u.name.indexOf(term) != -1) : this.users;
});

并添加一个不过滤的空白支票,并以此开始流。完成并完成。不要在不需要的地方增加复杂性。rxjs 建议在您的订阅函数中出现副作用,其他一切都应该是变革性的/功能性的,并且在控制器上设置一个值是一个副作用。

如果你想获得真正的反应,你可以投入一个异步管道以获得良好的衡量标准

this.filteredUsers$ = this.filter.valueChanges.pipe(startWith('')).tap(
  (term) => {
    return (term) ? this.users.filter(u => u.name.indexOf(term) != -1) : this.users;
});

然后在 HTML 而不是

*ngFor="let user of filteredUsers"

做:

*ngFor="let user of filteredUsers$ | async"

这里的好处是自动订阅清理和更好地支持 onpush 更改检测。


推荐阅读