我正在尝试获取当前用户的活动作业列表:
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);
})
);
}
});
问题始于过滤。根据官方文档,其参数的正确部分应返回布尔值,因此就像我的情况一样。但它仍然会返回整个条目而不过滤它们。
答案 0 :(得分:2)
您要返回Array.map
来电的结果,请查看其返回值:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
您可能希望使用map
代替filter
:
.snapshotChanges().map(...)
.map(val => val.map(job => {
return (job.employer == data.uid || job.employee == data.uid);
}));
答案 1 :(得分:1)
我相信您想要反转地图并过滤运算符。
map
(filter
将一个数组转换为另一个数组,.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 )
})
以减少数组。
或者您可以将过滤器链接到执行类型转换的地图
var innerTag = document.querySelector('.form-control-tag-inner');
var innerInput = document.querySelector('#conv-dest');
var innerContent = document.createRange().createContextualFragment('<span class="label label-default"><span class="text-">nick</span><span class="close close-tag" aria-hidden="true">×</span><input type="hidden" name="participants[nick]" value="nick"></span>');
innerTag.insertBefore(innerContent, innerInput);
// sample event, attached on newly added content
var innerCross = document.querySelector('.form-control-tag-inner .close');
innerCross.onclick = function(){
console.log( 'click' );
return false;
};
答案 2 :(得分:0)
不确定理解整个问题,但可能是:
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))
)
);