【问题标题】:How to filter data using RxJS observables based on a pattern如何使用基于模式的 RxJS 可观察对象过滤数据
【发布时间】:2017-04-02 08:18:52
【问题描述】:

我在 Angular 2 应用程序中使用 RxJS 可观察对象。我正在尝试获取员工列表,如果员工 ID 以“MA”结尾,我不希望将它们添加到列表中。以下是我的代码:

    getEmployees(): any {
    return this.employeeService.get("http://localhost:9080/employees")
                .map((employees: any) => employees.map((employee: any) => {
                    let empcode: string = employee.empcode;
                    if (empcode.lastIndexOf("MA") == -1) {
                        return { empText: empcode+ ' - ' + employee.empName, data: employee};
                    }
                        return { empText: '', data : null};
                }));
}

我无法过滤记录,它正在返回所有值。我有两个返回语句,所以它返回所有值,但如果我删除其中一个,我会收到以下错误:

返回表达式中不存在最佳通用类型

web服务返回的json格式如下:

{
employeeCode: "EMPCT", 
employeeName: "Tom", 
role: "HR"
}

那么您能否告诉我在这种情况下过滤 Web 服务返回的记录的最佳方法是什么?

【问题讨论】:

    标签: angular typescript rxjs5


    【解决方案1】:
    getEmployees(): any {
        return this.employeeService.get("http://localhost:9080/employees")
                    .map((employees: any) => {
                        let filtered = employees.json().filter((employee) => {
                          let empcode: string = employee.empcode;
                          if (ifscode.lastIndexOf("MA") == -1) {
                            return true;
                          } else {
                            return false;
                          }
                        });
                      return filtered;
                    }));
    }
    

    【讨论】:

    • 我想返回 empcode 和员工姓名,而不是 true 和 false,如果员工代码以 MA 结尾,那么我不想返回那个员工。你能告诉我如何使用您建议的解决方案。
    • 有了它,您将获得从 API 返回的员工的所有详细信息。检查一次,如果可能的话,用你从 API 得到的响应更新你的问题。
    • 我已经更新了 API 返回的示例 json。它以该格式返回我的记录。在问题中,我提到了我希望返回数据的格式,那么我该如何使用上述解决方案来做到这一点。
    • 您是否通过在调用getEmployees 函数的组件中执行console.log 检查结果?
    • 我在 chrome 的网络选项卡中检查了结果,它仍然返回以 MA 结尾的代码的员工。
    【解决方案2】:

    为什么不使用filter 函数?

    getEmployees(): any {
      return this.employeeService.get("http://localhost:9080/employees")
                  .map((employees: any) => items.filter((employee: any) => {
                      let empcode: string = employee.empcode;
                      return ((ifscode.lastIndexOf("MA") == -1); 
                  }));
    }
    

    不确定 ifscode 来自哪里。无论如何,您应该使用过滤器。如果您需要进一步转换,可以链接 .map() 操作。

    【讨论】:

    • "为什么不使用过滤功能?"是的,他当然应该。但不是来自Arrayfilter。他应该使用来自Observable 的过滤器。见stackoverflow.com/a/40678593/2398593
    • 总的来说,我只同意你的观点,这里的序列是由数组组成的。 RX 过滤器将通过或阻止整个结果,在这种情况下这不是所需的行为
    • @Meir 我能够获得过滤后的记录。但我想将员工姓名+员工代码返回到组件。知道我该怎么做。
    • 在过滤器之后做你的原始映射(没有条件测试):items.filter(...).map(...)
    猜你喜欢
    • 2018-11-23
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多