rxjs可观察的重用逻辑

编程入门 行业动态 更新时间:2024-10-18 12:24:55
本文介绍了rxjs可观察的重用逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写一个有角度的文件上传组件.

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 dialog
  • remove : 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可观察的重用逻辑

本文发布于:2023-11-27 23:31:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640041.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:逻辑   rxjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!