首页 > 解决方案 > 相同订阅处理代码的更好的代码维护 [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);
  });

对于所有三种情况,它都是相同的代码,我试图避免重复三次。有任何想法吗?谢谢!

标签: angularrxjsobservable

解决方案


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);

推荐阅读