我目前正在创建一个系统,如果我成功地更新了一个请求,我就会在一个forkjoin中触发3个观测值,然后一旦这些观测值完成,就会触发 console.log('completeor finish'),否则如果没有完成,就什么都不做。
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观测值完成了,然后就会有console.log('finish')
目前的结果是服务完成。它 console.logs('finish')然后我的forkjoin触发
我发现这个问题的解决方案是,你不需要返回空()或of(),而是需要返回一个空的对象作为观察对象,这样Forkjoin仍然保持值,所以返回of({}),一切都很好。