角度2:如何使用可观察滤镜 [英] Angular 2: How to use Observable filter

查看:77
本文介绍了角度2:如何使用可观察滤镜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以像这样调用API的服务:

I have a service that calls the API like this:

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在该调用上实现过滤器功能,但是我无法使其正常工作.

Now I want to implement a filter function on that call using rxjs/add/operator/filter, but I can't get it to work properly.

这是我采用的方法:

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循环都不会产生任何结果.如果删除它,一切都会按预期进行.

But no matter what I filter on, the ngFor loop produces nothing as long as the filter is in there. If I remove it, everything works as expected.

我应该在map之前还是之后添加过滤器吗?

Am I supposed to add the filter before or after the map?

我可以像这样过滤响应JSON,还是需要使用其他语法?

Can I filter on the response JSON like that, or do I need to use another syntax?

示例JSON

以下是响应JSON的示例:

Here's an example of what the response JSON looks like:

data: [
    {
        "Type": 5,
        "Description": "Testing",
        "ID": "001525"
    }
]

推荐答案

filter()应该在map()之前还是之后取决于您要执行的操作.

Whether filter() should be before or after map() depends on what you want to do.

我想在您的情况下,map()应该在filter()之前,因为您要先从JSON解码数据然后对其进行过滤.如果filter()中的条件解析为false,则现在拥有的方式将不会返回任何内容,因为您要在整个response中使用in.也许这就是你要去的...

I guess in your case map() should go before filter() because you want to first decode data from JSON and then filter it. The way you have it now won't return anything if the condition in filter() resolves to false because you're using in on the entire response. Maybe this is what you're going for...

我不知道您的回复结构是什么,但我会选择更有意义的类似方法:

I don't know what your response structure is but I'd go with something like this which makes more sense:

map((response: Response) => response.json().data),
filter(data => data.Type === 5),

我将concatMap()from()结合使用,以将数组转换为可观察流:

I'd use concatMap() with from() to transform the array to an Observable stream:

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更新

Jan 2019: Updated for RxJS 6

这篇关于角度2:如何使用可观察滤镜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆