angular - ตัวดำเนินการ RXJS ไม่ทำงานกับ firebase
ฉันกำลังใช้ตัวดำเนินการ RXJS กับ observable ของ Firebase (distinct และ filter) นี่คือต้นไม้ Firebase ของฉัน นี่คือโค้ดของฉัน:
let places this.db.list(`users/${this.authProvider.getUID()}/visitedPlaces`,{
query:{
orderByChild:"googleId"
}
});
places.distinct((p)=>{
console.log(p)
return p.googleId;
}).
subscribe((snap)=>{
console.log(JSON.stringify(snap,null,2))
},(err)=>{
console.log(JSON.stringify(err,null,2))
},()=>{
console.log("completed");
});
ฉันกำลังพยายามแยกข้อมูลใน Firebase ตาม googleId ฉันไม่ได้รับข้อผิดพลาดใด ๆ แต่รายการที่แยกออกมานั้นใช้งานไม่ได้
มีใครช่วยหรือมีเหตุผลสำหรับเรื่องนี้ไหม? ขอบคุณ.
คำตอบ #1
ฟังดูเหมือนว่าคุณกำลังใช้ตัวดำเนินการ distinct กับอาเรย์ แทนที่จะเป็นสตรีมของอ็อบเจ็กต์ ดังนั้น p จึงเป็นอาเรย์ในตัวดำเนินการ distinct ของคุณ แทนที่จะเป็นอ็อบเจ็กต์ภายในอาเรย์ตามที่คุณคาดหวัง คุณสามารถทำได้ด้วย JavaScript ธรรมดาใน map ดังนี้:
Rx.Observable.of([
{ id: 1},
{ id: 2},
{ id: 1},
{ id: 3},
{ id: 2}
]).map(x => x.reduce((a, c) => {
if (!a.some(y => y.id === c.id)) {
a.push(c);
}
return a;
}, [])
).subscribe(x => { console.log(x); });<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>หรือคุณสามารถขยายอาเรย์โดยใช้ flatMap ดังนี้:
Rx.Observable.of([
{ id: 1},
{ id: 2},
{ id: 1},
{ id: 3},
{ id: 2}
])
.flatMap(x => x)
.distinct(x => x.id)
.subscribe(x => { console.log(x); });<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>