angular - 相同订阅处理代码的更好的代码维护 [Angular/Rxjs]
问题描述
假设我有以下代码:
this.myService.doSomething1.subscribe(SAME CODE FOR SUCCESS|ERROR|COMPLETE);
this.myService.doSomething2.subscribe(SAME CODE FOR SUCCESS|ERROR|COMPLETE);
this.myService.doSomething3.subscribe(SAME CODE FOR SUCCESS|ERROR|COMPLETE);
如何为这些相同的订阅编写易于维护的代码,这样我就不必重复相同的代码三次或更多次?为了清楚起见,重复的代码如下:
(success: any) => {
this.sucess= true;
},
(err: HttpErrorResponse) => {
console.log(err);
});
对于所有三种情况,它都是相同的代码,我试图避免重复三次。有任何想法吗?谢谢!
解决方案
You can use multiple functions that you maintain centralized and pass them.
const suc = (value:object) => {
// do something
};
const err = (error: HttpErrorResponse) => {
// handle error
}
const complete = () => {
// handle complete
}
this.myService.doSomething1.subscribe(suc,err,comlete);
this.myService.doSomething2.subscribe(suc,err,comlete);
this.myService.doSomething3.subscribe(suc,err,comlete);
if you want to go further and build a composit object and use the spread operator to only have a single variable:
const default_sub = [suc,err,complete]
this.myService.doSomething1.subscribe(...default_sub);
推荐阅读
- regex - 正则表达式获取 html 标签之间的字符串:在结束标签的第一个匹配项处停止选择
- sql - 无法使用 H2 数据库在我的表中添加外键
- javascript - 排除外部库捆绑在 webpack 中?
- linux - 如何运行另一个程序并将其仅输出到终端的特定部分
- mysql - phpMyAdmin 中的 MySQL 触发器
- javascript - 一个月后删除帖子
- c# - 我怎样才能有 Nullable
- java - 使用 Play 连接到 WebSocket!2.5
- asp.net - 自定义授权过滤器以检查电子邮件确认和资源所有权
- node.js - Uppy 文档未定义 node.js