【问题标题】:Why do the RxJS filter method not work for me为什么 RxJS 过滤方法对我不起作用
【发布时间】:2019-04-17 15:01:33
【问题描述】:

在使用 RxJS 运算符时遇到问题。

我的端点返回Observable<Array<TaskReprintReasonCode>>

然后我使用异步管道订阅这个 observable。

this.reason$ = this.taskService.getTaskReprintReasonCodes();

这很有效,直到我需要从该原因列表中过滤或映射某些内容。

this.reasons$ = this.taskService
  .getTaskReprintReasonCodes()
  .pipe(filter(r => r.reasonDescription === "New"));

我猜这与我定义从数据库返回的类型的方式有关。命名Observabe<INSERTTYPE[]>是不好的做法

【问题讨论】:

  • 您正在访问一个数组。您很可能希望使用数组过滤器,查看您的代码。 Observable 地图运算符会更有意义吗? this.reasons$ = this.taskService.getTaskReprintReasonCodes().pipe(map(rArray => rArray.filter(r => r.reasonDescription === 'New'))).
  • 这是您需要知道的吗?您似乎将 RxJs 中的过滤器与数组中的过滤器混为一谈。数组生成新的过滤列表,RxJs 过滤流并阻止发出对过滤器无效的项目。
  • 我可以推荐在我的视频课程中了解更多关于 rxjs6 的信息:packtpub.com/web-development/hands-rxjs-web-development-video

标签: angular rxjs observable rxjs5


【解决方案1】:
Observable<Array<TaskReprintReasonCode>>

定义TaskReprintReasonCode 对象的集合。

您可以使用map() 运算符来修改流中项目的值。如果您想将数组缩减为仅具有"new" 属性的数组,则可以使用数组原型中的filter()

    this.taskService.getTaskReprintReasonCodes().pipe(
        map((arr:TaskReprintReasonCode[]) => {
             return arr.filter(r => r.reasonDescription === 'New');
        )
    )

Array.filter()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Rxjs.map()

https://www.learnrxjs.io/operators/transformation/map.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    相关资源
    最近更新 更多