angular - 使用 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()
任何帮助将不胜感激。
解决方案
你是对的,点击不是“正确”的方式......正确的方式是在订阅中进行......
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 更改检测。
推荐阅读
- python - 正则表达式中的枚举
- python - 使用 python 代码运行 caffe 模型时出现字典键错误
- node.js - 由于未处理的承诺异常,数据库未在 mongodb atlas 中运行
- mysql - UNION 2 带有计算列的选择查询
- angular - 在 Angular 中为动态 mat-table 创建一个通用管道
- javascript - React.PropsWithChildren 除了 `children` 没有其他道具?
- ios - SwiftUI 网格项内存泄漏
- swift - makeAlert 函数总是返回 False
- python-3.x - 请求如何发送有效负载以登录并确认帖子成功
- android - 如何在 viewModel Kotlin Android 中保护参数?