我有一个像这样调用 API 的服务:
return this._http
.post(appSettings.apiUrl + 'SomeController/SomeAction', params, {withCredentials: true, headers: this.headers})
.timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
.map((response: Response) => response.json().data);
现在我想使用 rxjs/add/operator/filter
在那个调用上实现一个过滤器函数,但我无法让它正常工作。
这是我采用的方法:
return this._http
.post(appSettings.apiUrl + 'SomeController/SomeAction', params, {withCredentials: true, headers: this.headers})
.timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
.filter(response => response.json().data.Type === 5)
.map((response: Response) => response.json().data);
但是无论我过滤什么,只要过滤器在其中,ngFor
循环就不会产生任何结果。如果我删除它,一切都会按预期进行。
我应该在 map
之前还是之后添加过滤器?
我可以像那样过滤响应 JSON,还是需要使用其他语法?
示例 JSON
这是响应 JSON 的示例:
data: [
{
"Type": 5,
"Description": "Testing",
"ID": "001525"
}
]
最佳答案
filter()
应该在 map()
之前还是之后取决于您想要做什么。
我想在你的情况下 map()
应该在 filter()
之前,因为你想先从 JSON 解码数据然后过滤它。如果 filter()
中的条件解析为 false
,您现在拥有它的方式将不会返回任何内容,因为您在整个 response
。也许这就是您想要的...
我不知道您的响应结构是什么,但我会选择这样更有意义的结构:
map((response: Response) => response.json().data),
filter(data => data.Type === 5),
编辑:
我将使用 concatMap()
和 from()
将数组转换为 Observable 流:
pipe(
map(content => response.json().data),
concatMap(arr => Observable.from(arr)),
filter(item => item.Type === 5),
).subscribe(val => console.log(val));
查看现场演示:http://plnkr.co/edit/nu7jL7YsExFJMGpL3YuS?p=preview
2019 年 1 月:针对 RxJS 6 进行了更新
关于 Angular 2 : How to use Observable filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40100530/