While attempting to filter data from an external source using the RxJS filter on Observables, I encountered an issue where all records were returned instead of just the ones meeting the filtering criteria. This problem occurred when the code was within a library function rather than at the UI level.
To demonstrate the problem, I created a simplified version:
import { Observable, of } from 'rxjs';
import { filter } from 'rxjs/operators';
export interface A {
name: string;
age: number;
}
export function Get(Age: number): Observable<A[]> {
const source: Observable<A[] | null> = of([
{ name: 'Joe', age: 31 },
{ name: 'Bob', age: 25 }
]);
console.log(Age)
return source.pipe(filter((person, index) => person[index].age >= Age));
}
const example = Get(30).subscribe(val => {
val.forEach((OneRecord: A) => {
console.log(OneRecord)
})
});
Even though the filter should limit the result to one record, it returns both records:
30
>{name: 'Joe', age: 31}
>{name: 'Bob', age: 25}
Interestingly, when I move the subscribe() and console.log into the function, the filtering works as expected. I'm unsure why the filter is not restricting the observable output as intended?