rxjs可观察的重用逻辑 [英] rxjs observable reusing logic
问题描述
我正在编写一个有角度的文件上传组件.
I'm writing a angular file-upload component.
成功上传后,它会显示一个通知和两个按钮:
Upon successful upload, it displays a notice and two buttons:
-
replace
:删除上传的文件并打开文件选择器对话框 -
remove
:删除上传的文件并显示通知
replace
: deletes uploaded file and opens the file-selector dialogremove
: deletes uploaded file and displays a notice
删除上传的文件意味着向后端系统发出HTTP DELETE请求并处理可能的失败和重试.
Deleting 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?
谢谢!
推荐答案
您可以使用管道方法来创建自定义运算符,如下所示:
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())
);
}
管道功能应从rxjs导入:
The pipe function should be imported from rxjs:
import { pipe } from "rxjs";
这篇关于rxjs可观察的重用逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!