Gle*_*ter 9 observable rxjs angular
我有一个调用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);
Run Code Online (Sandbox Code Playgroud)
现在我想在该调用上实现一个过滤函数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);
Run Code Online (Sandbox Code Playgroud)
但无论我过滤ngFor什么,只要过滤器在那里,循环就不会产生任何效果.如果我删除它,一切都按预期工作.
我应该在之前或之后添加过滤器map吗?
我可以像这样过滤响应JSON,还是需要使用其他语法?
示例JSON
以下是JSON响应的示例:
data: [
{
"Type": 5,
"Description": "Testing",
"ID": "001525"
}
]
Run Code Online (Sandbox Code Playgroud)
mar*_*tin 16
是否filter()应该在之前或之后map()取决于您想要做什么.
我想在你的情况下map()应该去,filter()因为你想先从JSON解码数据,然后过滤它.你现在拥有它的方式不会返回任何东西,如果因为你正在使用整个条件而filter()解决.也许这就是你想要的......falseresponse
我不知道你的反应结构是什么,但我会选择这样的东西更有意义:
map((response: Response) => response.json().data),
filter(data => data.Type === 5),
Run Code Online (Sandbox Code Playgroud)
编辑:
我将使用concatMap()with from()将数组转换为Observable流:
pipe(
map(content => response.json().data),
concatMap(arr => Observable.from(arr)),
filter(item => item.Type === 5),
).subscribe(val => console.log(val));
Run Code Online (Sandbox Code Playgroud)
观看现场演示:http://plnkr.co/edit/nu7jL7YsExFJMGpL3YuS?p = preview
2019年1月:更新了RxJS 6
| 归档时间: |
|
| 查看次数: |
39132 次 |
| 最近记录: |