javascript - การเชื่อมต่อ observables ด้วย switchmap และ forkjoin ไม่ทำงานตามที่คาดหวัง angular typescript rxjs
ตอนนี้ฉันกำลังพยายามสร้างระบบที่ถ้าฉันอัปเดตคำขอได้สำเร็จ ฉันจะเรียกใช้ออบเซอร์เวเบิล 3 ตัวใน forkJoin แล้วเมื่อพวกมันเสร็จสิ้นก็จะ console.log('complete/or finish') มิฉะนั้นถ้าไม่เสร็จก็ไม่ทำอะไร อย่างไรก็ตามตอนนี้ออบเซอร์เวเบิลเหล่านั้นทำงานเสร็จก่อนที่ forkJoin จะเสร็จ และฉันไม่เข้าใจเลยว่าเกิดอะไรขึ้น
copyAttachments(): Observable<any> {
if (this.model.attachments.length > 0) {
return this.attachmentService.copyAttachments(this.model.attachments, this.model.id);
}
return empty();
}
uploadAttachments(): Observable<any> {
this.showAttachmentsUploadingModal = true;
const formData = new FormData();
if (this.formAttachments.length > 0) {
this.showAttachmentsUploadingModal = true;
this.formAttachments.forEach(file => {
formData.append('files', file, file.name);
});
}
// uploading empty formData will still trigger creation of default folder structure
return this.attachmentService.uploadAttachments(formData, this.model.id);
}
uploadCustomerData(): Observable<any> {
this.showAttachmentsUploadingModal = true;
const formData = new FormData();
if (this.formCustomerData.length > 0) {
this.showAttachmentsUploadingModal = true;
this.formCustomerData.forEach(file => {
formData.append('files', file, file.name);
});
return this.attachmentService.uploadCustomerData(formData, this.model.id);
}
return empty();
}handleAttachments(): Observable<any> {
return forkJoin
(
this.copyAttachments(),
this.uploadCustomerData(),
this.uploadAttachments()
)
}
updateRequest() {
this.myservice
.updateRequest(this.model)
.pipe(
switchMap((saveResult: boolean) => {
this.showSubmittingModal = false;
if (saveResult === true) {
return this.handleAttachments();
} else {
return empty();
}
}),
)
.pipe(finalize(() => {
console.log('finish')
}))
.subscribe(
response => {
// todo: do anything with this response from uploadAttachments()?
this.showAttachmentsUploadingModal = false;
},
error => {
location.reload();
},
() => {
console.log('complete')
}
);
}ผลลัพธ์ที่คาดหวังคือบริการของฉันเสร็จสมบูรณ์ จากนั้น forkjoin observables ของฉันจะเสร็จสมบูรณ์ แล้วมันจะ console.log('finish')
ปัจจุบันผลลัพธ์คือบริการเสร็จสมบูรณ์ มัน console.logs('finish') แล้วจากนั้น forkjoin ของฉันก็ทำงาน
คำตอบ #1
วิธีแก้ปัญหาที่ฉันพบคือ แทนที่จะส่งค่า empty() หรือ of() คุณต้องส่งวัตถุว่างเป็น observable แบบนี้ ForkJoin จะยังคงรักษาค่าของมัน ดังนั้นให้ส่งค่า of({}) และทุกอย่างก็จะเรียบร้อย