I have a method to update a 'Request' on a MySQL database. This request can optionally contain attachments, in which case I need to make additional HTTP requests to update or add the attachment records (to a different DB table) and upload the files.
I have a functional method to update the requests and optionally skip the attachments HTTP requests, but would like to know a more succinct way to achieve this. In general, I am new to Angular and RXJS, so the approach and use of rxjs operators is likely, not optimal.
Basically, I am looking for the best way to conditionally chain in some optional observables before subscription, or skip straight to the subscription.
I was looking at potential solutions with iif, returning Observable.empty() and different rxjs operators, but these seem to be options within the map functions when I just want to skip them altogether.
onUpdateRequest() {
// if there are no attachments added to the request
if (this.attachments.length <= 0) {
this.callUpdateRequest().subscribe(() => {
// some page and form tidy up
});
// there are attachments, so process the new request and then file uploads
} else {
this.callUpdateRequest().pipe(
switchMap(() => {
return of(this.attachments);
}),
mergeMap(attachments => {
return attachments.map(attachment => {
return attachment;
});
}),
mergeMap(attachment => {
return this.attachmentsService.addAttachmentFile(attachment)
.pipe(map(fileData => {
return fileData;
}));
}),
mergeMap(fileData => {
return this.attachmentsService.addAttachment(
this.requestId, fileData.fileUrl
).pipe(
map(attachments => {
return attachments;
})
);
}),
takeLast(1)
)
.subscribe(() => {
// some page and form tidy up
});
)
}
private callUpdateRequest() {
return this.requestsService.updateRequest(
// all the request params
)
}