Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i am not able to filter records with rxjs filter?

In the angular project, i have rxjs filter through which i am not able to filter records. My function is here

public getOrders(type: string, filterObj = {}, otherParams = {}): Observable<{ name: string; qt: number }[]> {
   return this.http.get(apiUrl, { params: { filter: JSON.stringify(filterObj), ...otherParams},
   })
   .pipe(map((res: any) => res.payload))
   .pipe(filter((order: any) => order.name && /\S/.test(order.name)));
}

It’s not filtering the records. It’s not returning any values.

But if i do like this so it’s working correctly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public getOrders(type: string, filterObj = {}, otherParams = {}): Observable<{ name: string; qt: number }[]> {
   return this.http.get(apiUrl, { params: { filter: JSON.stringify(filterObj), ...otherParams},
   })
   .pipe(map((res: any) => res.payload.filter((order: any) => order.name && /\S/.test(order.name))))
}

what’s going wrong here?

>Solution :

Well, there’s a difference between rxjs filter and the Array.filter.

The rxjs filter is used to filter out observable emissions that you don’t need – supposing that your source observable emits more than one value (which is not the case with httpClient.get)

The Array.filter, the one that you do need, in order to filter out some elements inside an array is a method that returns an array which contains the elements that correspond to your filter criteria. So in order to do this the right way, you could write something like this:

public getOrders(
  type: string,
  filterObj = {},
  otherParams = {}
): Observable<{ name: string; qt: number }[]> {
  return this.http
    .get(apiUrl, {
      params: { filter: JSON.stringify(filterObj), ...otherParams },
    })
    .pipe(
      map((res: any) => res.payload),
      map((orders) =>
        orders.filter((order: any) => order.name && /\S/.test(order.name))
      )
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading