Issue
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?
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))
)
);
}
Or simply omit the second map
and do it the same way you did it the second time when it worked correctly.
Answered By - Octavian Mărculescu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.