Angular RXJS-订阅触发多次。具有多个if-else条件的嵌套订阅

Angular RXJS-订阅触发多次。具有多个if-else条件的嵌套订阅,angular,if-statement,rxjs-observables,angular-observable,Angular,If Statement,Rxjs Observables,Angular Observable,要优化以下代码: 多个if-else语句中的多个订阅 考虑:- getList(): void { this.subs.sink = this.subscription1.subscribe((user) => { if (user) { this.method1(); } }); } method1() { //code //code if (condition){ //code } else { this.method2()

要优化以下代码: 多个if-else语句中的多个订阅

考虑:-

getList(): void {
    this.subs.sink = this.subscription1.subscribe((user) => {
      if (user) {
        this.method1();
      }
    });
  }

method1() {
//code
//code
if (condition){
//code
} else {
this.method2()
}

method2(){
 this.subs.sink = this.subscription2.subscribe(
      (response) => {
if(){
//code
} else {
this.method3();
}
}

method3(){
this.subs.sink = this.subcription3.subscribe(
      (response) => {
//code
}
}
这将导致触发多个订阅


任何帮助。非常感谢。

有多种方法可以简化多个订阅。这取决于
//code
到底代表什么。如果大多数
//code
是相同的,那么您可以使用
过滤器来应用条件

以下方法假定每个
//code
块都是唯一的。它使用
switchMap
从一个可观察对象映射到另一个可观察对象。如果您不希望将可观测值转发到订阅的
next
块,可以返回RxJS
EMPTY
常量。它将基本上完成可观察的

从'rxjs'导入{EMPTY};
从“rxjs/operators”导入{switchMap};
getList():void{
this.subs.sink=this.subscription1.pipe(
switchMap((用户:任意)=>{
//代码
如果(条件){
//代码
返回空;
}
返回此文件。订阅2;
}),
开关映射((响应:任意)=>{
如果(条件){
//代码
返回空;
}
返回此文件。订阅3;
})
).订阅({
下一步:(响应:任意)=>{
//来自“this.subscription3”的响应`
//代码
},
错误:(错误:任意)=>{
//处理错误
}
});
}