I'm writing a angular file-upload component.
Upon successful upload, it displays a notice and two buttons:
replace
: deletes uploaded file and opens the file-selector dialogremove
: deletes uploaded file and displays a noticeDeleting the uploaded file means making a HTTP DELETE request to a backend system and handling possible failure and retries.
_handleReplace() {
this.replaceClicked$.pipe(
tap((x) => this._backend.delete(this.file, this.fieldName)),
tap((x) => openFileSelectorDialog())
);
}
_handleRemove() {
this.replaceClicked$.pipe(
tap((x) => this._backend.delete(this.file, this.fieldName)),
tap((x) => displayNotice())
);
}
In this snippet I'm not dealing with possible failure and retries.
How can I extract the deletion logic to avoid repeating it in two methods?
Or more generically, how can I apply common transformations on two different observables?
Thank you!
You can use the pipe method to create a custom operator like this:
deleteFile = () => pipe(
tap((x) => this._backend.delete(this.file, this.fieldName))
);
_handleReplace() {
this.replaceClicked$.pipe(
deleteFile(),
tap((x) => openFileSelectorDialog())
);
}
_handleRemove() {
this.replaceClicked$.pipe(
deleteFile(),
tap((x) => displayNotice())
);
}
The pipe function should be imported from rxjs:
import { pipe } from "rxjs";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With