Angular 2:如何使用 Observable 过滤器 [英] Angular 2: How to use Observable filter

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

问题描述

我有一个像这样调用 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.也许这就是你想要的......

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() 将数组转换为 Observable 流:

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

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

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