Angular 2 http-在返回可观察对象之前对其进行过滤 [英] Angular 2 http - filter the observable before returning it

查看:69
本文介绍了Angular 2 http-在返回可观察对象之前对其进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用中,我已定义如下:

In service I have this defined:

getAllHTTP(): Observable<IUser[]> {
   return this.http.get(`${this.url}/users`)
              .map(res => res.json())
              .catch(err => Observable.throw(err));
}

并在组件中:

ngOnInit() {
   const self = this;
   this._uService.getAllHTTP().subscribe(
      function (data) {
        console.log(data);
        self.listOfUsers = data
      },
      (error) => console.error(error)
   );
}

所以现在我想在将可观察对象传递给组件之前过滤数据,我这样做了:

So now I wanted to filter the data before passing the observable to component and I did this:

  getAllHTTP(): Observable<IUser[]> {
     return this.http.get(`${this.url}/users`)
                .map(res => res.json())
                .filter(<IUser>(x) => x.id > 2)
                .catch(err => Observable.throw(err));
  }

,它不起作用.过滤器中的 x 是实际数组,而不是数组中的项.这真的很奇怪,我认为它与RXjs无关,因为它的工作方式与本示例中的假设相同:

and it doesn't work. The x in filter is an actual array, not an item in the array. This is really odd and I think it has nothing to do with RXjs, because it works like it's suppose to in this example: http://jsbin.com/nimejuduso/1/edit?html,js,console,output

因此,我做了一些挖掘工作,显然我应该使用flatMap.好的,我做到了,用 flatMap 替换了 map ,但是现在出现了这个错误:

So I did some digging and apparently I should be using flatMap. OK, I did that, replaced map with flatMap but now I get this error:

找不到其他支持对象'[object Object]'

Cannot find a differ supporting object '[object Object]'

显然,当我订阅时,我曾经获得一个数组,现在一次获得一个对象...为何Angular2的行为如此?还是这个RXjs?

So apparently when I subscribe, I used to get an array and now I get one object at a time... Why is Angular2 behaving like that? Or is this RXjs after all?

推荐答案

您正在对可观察的流应用过滤器,从而对流中的事件进行过滤,而不对数组中的元素进行过滤,在这种情况下,该元素是流中的单个事件

You are applying a filter on the observable stream, thus filtering events within the stream and not elements within the array which in this case is a single event in the stream.

您需要做的是:

getAllHTTP(): Observable<IUser[]> {
     return this.http.get(`${this.url}/users`)
                .map(res => res.json()
                            .filter(<IUser>(x) => x.id > 2))
                .catch(err => Observable.throw(err));
}

您链接的示例如此工作,因为 Observable.from 正在为可观察对象创建一个值序列,而不是为整个数组添加一个单一值.这就是 Observable.filter 如此工作的原因,因为数组元素一次传递一个.在文档.

The example you linked is working like that because Observable.from is creating a sequence of values for the observable, rather than a singe value being the whole array. This is why the Observable.filter is working as it does, because the array elements are passing by one at a time. See more details in the docs.

这篇关于Angular 2 http-在返回可观察对象之前对其进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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