Filtering Observable with Rxjs

寵の児 提交于 2020-02-06 08:25:48

问题


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.


回答1:


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 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 )
})



回答2:


You're returning the result of the Array.map call, see its return value: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

It looks like you maybe want to use map instead of filter:

.snapshotChanges().map(...)
.map(val => val.map(job => {
   return (job.employer == data.uid || job.employee == data.uid);
}));



回答3:


Not sure to understand the whole problem, but it might be something like:

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


来源:https://stackoverflow.com/questions/47122974/filtering-observable-with-rxjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!