如何使用基于模式的RxJS observables过滤数据
我在我的Angular 2应用程序中使用RxJS observables。我试图获取员工列表,如果员工ID以'MA'结尾,我不希望他们成为添加到列表中。以下是我的代码:如何使用基于模式的RxJS observables过滤数据
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};
}));
}
我不能够过滤记录,它返回我所有的values.I有两个return语句,以便它返回所有的价值,但如果我删除其中的一个,我得到以下错误:
没有最好的常见类型的返回公式中存在
由Web服务返回的JSON是按以下格式:
{
employeeCode: "EMPCT",
employeeName: "Tom",
role: "HR"
}
那么你能否让我知道在这种情况下过滤Web服务返回的记录的最佳方式是什么。
为什么不使用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()
操作。
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,并且incase雇员代码以MA结束,然后我不想退还该员工。请让我知道如何使用您建议的解决方案来实现这一点。 – Valla
有了它,您将获得从API返回的所有员工详细信息。检查一次,如果可能的话,用你从API获得的回应更新你的问题。 – ranakrunal9
我已经更新了API返回的示例json。它以这种格式返回我的记录。在这个问题中,我提到了我希望返回数据的格式,所以我如何使用上面提到的解决方案来做到这一点。 – Valla
“为什么不使用过滤功能?”是的,他当然应该。但不是'Array'中的'filter'。他应该使用'Observable'中的过滤器。请参阅http://*.com/a/40678593/2398593 – Maxime
一般来说,我只同意你这里的序列是由数组组成的。 RX过滤器将通过或阻止整个结果,在这种情况下,这不是期望的行为 – Meir
我的坏,你是绝对正确的:) – Maxime