Issue
I am sending a GET request from a service to an API, which returns a JSON array. I am having a hard time filtering the results. I was thinking of using rxjs find or filter, but I could not manage to do it.
Here's the original request:
TestRequest(): Observable<any> {
const nativeCall = this.nativeHttp.get('https:***' + this.formattedDate,
{ },
{'x-api-key': this.value, 'Content-Type': 'application/json'});
return from(nativeCall).pipe(
map(Results => JSON.parse(Results.data))
);
}
And the format of the data from the API looks like this:
When I subscribe to the observable, I get all data from the JSON Array. I need to filter only one specific item from [bc], which fulfills the requirements. And I will later visualize it in template.
I would be extremely grateful for any advice.
Solution
The filter operator of RxJS helps to filter entire results of your observable stream.
In your case the best RxJS operator to use is a simple map, which can transform your result to a new shape of data.
Finally, to get one element from an array use can use the es6 array method find.
Example:
const predicateFn = element => ...; // specify requirements.
return from(nativeCall).pipe(
map(Results => JSON.parse(Results.data)),
map(data => data.bc.find(e => predicateFn(e))) // create another map is optional
);
Answered By - Yasser Nascimento

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.