过滤可观察的

时间:2020-07-19 12:10:25

标签: angular ionic-framework rxjs observable

我正在将GET请求从服务发送到API,该API返回JSON数组。我很难过滤结果。我当时在考虑使用rxjs查找或过滤器,但我无法做到这一点。

这是原始请求:

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))
);

}

API的数据格式如下:

enter image description here

当我订阅可观察对象时,我从JSON数组获取所有数据。 我只需要过滤[bc]中满足要求的一个特定项目。 我稍后将在模板中对其进行可视化。

我将非常感谢您提供任何建议。

2 个答案:

答案 0 :(得分:1)

您可以尝试

TestRequest(): Observable<any> {
const nativeCall = this.nativeHttp.get('https:***' + this.formattedDate,
{ },
{'x-api-key': this.value, 'Content-Type':  'application/json'});
return from(nativeCall).subscribe(result => {
 const filterdArr = result['data'].filter(element => yourCondition);
});
}

答案 1 :(得分:1)

RxJS的filter运算符有助于过滤可观察流的全部结果。

对于您来说,最好的RxJS运算符是一个简单的map,它可以将结果转换为新的数据形状。

最后,要使用数组中的一个元素,可以使用es6数组方法find

示例:

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
);
相关问题