[英]Filtering Observable with 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. 但是它仍然返回我整个条目而不过滤它们。
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 您将返回Array.map
调用的结果,请参见其返回值: 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
: 看来您可能想使用map
而不是filter
:
.snapshotChanges().map(...)
.map(val => val.map(job => {
return (job.employer == data.uid || job.employee == data.uid);
}));
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). ( map
将一个数组转换为另一个数组, filter
以缩小数组)。
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 )
})
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))
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.