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.
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?
CodePudding user response:
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))
)
);
}
Or simply omit the second map
and do it the same way you did it the second time when it worked correctly.
CodePudding user response:
Looks like your payload is an array
- no wonder it does not work as you would like it to work
What you essentialy do is
const arr:any = [];
if(arr.name){///whatever}
does that make sense? Rather not.
your filter
works as it should work, your code is badly written as it should not be. Therfore as I wrote
In the angular project, i have rxjs filter that is not working the way it should.
was a bold statement
Stop using any
everywhere, start using typing system (the main reason behind TS) and you will not have such problems in the future