使用Rxjs过滤可观察到的 [英] Filtering Observable with Rxjs

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

问题描述

我正在尝试获取当前用户的活动作业列表:

I'm trying to get a list of active jobs for the current user:

jobListRef$: Observable<Job[]>;
...
this.afAuth.authState.take(1).subscribe(data => {
  if (data && data.uid) {
    this.jobListRef$ = this.database.list<Job>('job-list', query => {
         return query.orderByChild("state").equalTo("active");
    })
    .snapshotChanges().map(jobs => {
         return jobs.map(job => {
              const $key = job.payload.key;
              const data = { $key, ...job.payload.val() };
              return data as Job;
         });
    })
    .filter(val =>
         val.map(job => {
              return (job.employer == data.uid || job.employee == data.uid);
         })
    );
  }
});

问题仅从过滤开始.根据官方文档,其参数的正确部分应返回布尔值,就像我的情况一样.但是仍然返回我整个条目而不过滤它们.

The problem begins only at the filtering. According to the official documentation the right part of its argument should return boolean, so like in my case. But still it returns me whole entries without filtering them.

推荐答案

我相信您想反转地图和过滤器运算符.

I believe you want to reverse the map and filter operators.

.map((jobs: Job[]) =>
  jobs.filter((job: Job) => job.employer === data.uid || job.employee === data.uid )
);

(map将一个数组转换为另一个数组,filter缩小数组).

(map to transform one array into another, filter to reduce the array).

或者您可以将过滤器链接到执行类型转换的地图上,

Or you can chain filter on to the map that performs the type-conversion,

.map(jobs => {
  return jobs.map(job => {
    const $key = job.payload.key;
    const data = { $key, ...job.payload.val() };
    return data as Job;
  })
  .filter(job => job.employer === data.uid || job.employee === data.uid )
})

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

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