angular - แปลงฟังก์ชันเป็น observable
มีใครช่วยทำฟังก์ชันนี้ให้เป็น observable ได้ไหม? ฉันต้องใช้มันเพื่อตรวจสอบว่ามีเอกสารอยู่แล้วตามคำค้นหรือไม่ ฉันจำเป็นต้อง subscribe มันเพื่อที่ฉันจะได้สร้างเอกสารถ้ายังไม่มี
ตอนนี้มันให้ข้อผิดพลาดกับฉัน:
ฟังก์ชันที่ประกาศประเภทไม่ใช่ 'void' หรือ 'any' ต้องคืนค่าหนึ่งค่า
exists(query: Vehicle): Observable<boolean>{
this.afs.collection('vehicles',
ref =>
ref
//queries
.where("country","==", query.country)
).snapshotChanges().subscribe(
res => {
if (res.length > 0){
//the document exists
return true
}
else {
return false
}
});
}//end exists()
แล้วฉันก็อยากเรียกมัน
this.vehicleService.exists({country:"USA})
.subscribe(x => {
if (x) {
//create a new doc
}
});
คำตอบ #1
แทนที่จะสมัครสมาชิก คุณควร pipe ผลลัพธ์ผ่าน map เพราะคุณต้องการเปลี่ยนผลลัพธ์ให้เป็นค่าบูลีน
ประการที่สอง คอมไพเลอร์กำลังแจ้งข้อผิดพลาดเพราะคุณได้ระบุชนิดของค่าที่คืนกลับ แต่จริง ๆ แล้วไม่ได้คืนค่าอะไรเลย ดังนั้นให้แน่ใจว่าคุณได้คืนค่า Observable
มันควรจะดูประมาณนี้:
exists(query: Vehicle): Observable<boolean> {
return this.afs.collection('vehicles',
ref =>
//queries
ref.where("country", "==", query.country)
).snapshotChanges().pipe(
// Use map to transform the emitted value into true / false
map(res => res && res.length > 0)
)
}//end exists()
