Valla Valla - 14 days ago 6
TypeScript Question

How to filter data using RxJS observables based on a pattern

I am using RxJS observables in my Angular 2 application.I am trying to get a list of employee and if the employee id ends with 'MA' i dont want them to be added to the list. Following is my code:

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};
}));
}


I am not able to filter the records and it is returning me all the values.I have two return statements so it is returning all the value but if I remove one of them I get the following error:

no best common type exists among return expressions

The json returned by the web service is in the following format:

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


So could you let me know what is the best way to filter records returned by the web service in this case.

Answer

Why not use the filter function?

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); 
              }));
}

not sure where the ifscode comes from. Anyways, you should use filter. If you need further transformation, you can chain a .map() operation.

Comments