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
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);
}));
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 )
})
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))
)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.