When utilizing RxJS, the process of filtering Observable data may not function as expected if the filtering is carried out within a separate function rather than directly within the subscribe

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?

Answer №1

The filter mentioned above will receive the entire persons array as the first parameter, instead of each individual person, since your observable is continuously streaming an array of people (Observable<A[]>).

To effectively filter items out of that list, you must transform the values streamed by the observable to a new value that filters out the non-matching records from the array:

export function FilterByAge(age: number): Observable<A[]> {
    const source: Observable<A[] | null> = of([
        { name: 'Joe', age: 31 }, 
        { name: 'Bob', age: 25 }
    ]);

    console.log(age);

    return source.pipe(
        map(people => people.filter(person => person.age >= age)
    );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for generating an injected and a const object instance?

How can an instance of class A obtain a dependency on an instance of class O, while remaining a singleton for others? @injectable() class O{} // A must be single instance! @injectable() class A{ constructor(o: O){ console.log( 'is A inst ...

The ngAfterViewChecked function seems to be caught in an endless loop

I am facing an issue where the <cdk-virtual-scroll-viewport> starts from the bottom, but I am unable to scroll up. I suspect that this problem is related to the use of AfterViewChecked. Even after trying AfterViewInit, the issue persists. @ViewChil ...

Ionic: Implementing a clear text field function when the ion-back-button is clicked

So I've created a feature where users can scan product barcodes using BarcodeScanner. Once the barcode is scanned, the product ID appears in a text field and is then sent to another page where an API call is made to display product details. On this pr ...

Error message stating: "Form control with the name does not have a value accessor in Angular's reactive forms."

I have a specific input setup in the following way: <form [formGroup]="loginForm""> <ion-input [formControlName]="'email'"></ion-input> In my component, I've defined the form as: this.log ...

The functionality of MaterializeCSS modals seems to be experiencing issues within an Angular2 (webpack) application

My goal is to display modals with a modal-trigger without it automatically popping up during application initialization. However, every time I start my application, the modal pops up instantly. Below is the code snippet from my component .ts file: import ...

Are union types strictly enforced?

Is it expected for this to not work as intended? class Animal { } class Person { } type MyUnion = Number | Person; var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Is this supposed to fail? var x: MyUnion = "jjj"; // Should this actually ...

Jest is unable to handle ESM local imports during resolution

I am encountering an issue with my Typescript project that contains two files, a.ts and b.ts. In a.ts, I have imported b.ts using the following syntax: import * from "./b.js" While this setup works smoothly with Typescript, Jest (using ts-jest) ...

Understanding Angular's Scoping Challenges

I have a function that retrieves an array and assigns it to this.usStates. main(){ this.addressService.getState().subscribe( (data:any)=>{ this.usStates = data; if(this.usStates.length===0) { this.notificationServic ...

Encountering an error message stating "The variable 'App' is declared but not used" when running the index.tsx function

This React project is my attempt to learn how to use a modal window. The tutorial I've been following on YouTube uses JavaScript instead of TypeScript for their React project. However, I'm facing some challenges. Could you possibly help me ident ...

Angular Error: Trying to access a property on an undefined variable

I'm currently having an issue with assigning data from an API to my Angular component file. Whenever I try to assign the data to my object variable, I receive an error stating: "cannot set property of undefined." Below is the relevant code snippet: C ...

Update the CSS styling of a parent div based on the active state of specific child divs

I have a class with 4 distinct columns. div class="mainContent"> <div class="left-Col-1" *ngIf="data-1"> </div> <div class="left-Col-2" *ngIf="!data-1"> ...

What is the best way to define the type of an object in TypeScript when passing it to a function

I am currently working on a function that accepts an object of keys with values that have specific types. The type for one field is determined by the type of another field in the same object. Here is the code: // Consider this Alpha type and echo function. ...

Experiencing a "HEROES not found" error while following an Angular guide

I've been diving into Angular with the tutorial provided on https://angular.io. However, I've hit a roadblock at step 4. Displaying a list where I'm encountering an error in HeroesComponent. Cannot find name 'HEROES' The cod ...

Can one invoke ConfirmationService from a different Service?

How can I declare an application-wide PrimeNG dialog and display it by calling ConfirmationService.confirm() from another service? Below is the HTML code in app.component.html: <p-confirmDialog [key]="mainDialog" class="styleDialog" ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

What is the best approach to access the reportProgress of several observables combined within a forkJoin?

I'm currently working on an Angular project where I need to upload multiple files through a form. Each file could be quite large, so I can't just do one POST request with all the files due to server size limits. It would be great if I could impl ...

Managing the Cache in IONIC2

After developing an App using IONIC 2, I realized that all my pages require loading through REST API. This can be frustrating as they get reloaded in every tab even when there are no updates. To improve this issue, I am planning to implement a caching sys ...

Karma Test Requirement: make sure to incorporate either "BrowserAnimationsModule" or "NoopAnimationsModule" when using the synthetic property @transitionMessages within your application

TEST FILE import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform- browser/animations'; import { ManagePageComponent } from './manage-page.component& ...

The Typescript Module augmentation seems to be malfunctioning as it is throwing an error stating that the property 'main' is not found on the type 'PaletteColorOptions'

Recently, I've been working with Material-UI and incorporating a color system across the palette. While everything seems to be running smoothly during runtime, I'm facing a compilation issue. Could someone assist me in resolving the following err ...

Why isn't my Promise fulfilling its purpose?

Having trouble with promises, I believe I grasp the concept but it's not functioning as expected in my project. Here is a snippet of my code : (I am working with TypeScript using Angular 2 and Ionic 2) ngOnInit() { Promise.resolve(this.loadStatut ...