RxJS:如何在嵌套订阅订阅之间组织订阅

时间:2020-03-06 15:15:02

标签: javascript angular typescript rxjs observable

在Angular应用程序中,我进行了以下处理:

  • OnInit从主题调用(SubjectOne)启动子订阅

  • 当有来自SubjectOne的新数据时,

    ,如果某些条件得到验证;我重新使用这些数据来发起第二次呼叫,这是来自服务呼叫的http呼叫。

这是我的代码

MyComponent.ts:

  ngOnInit() {
    this.getFirstTreatment();
  }

  getFirstTreatment() {
    this.subscriptionOne = this.myService.subjectOne.subscribe((data) => {
      this.myValue = data['myValue'];
      this.getSecondTreatment(data['myValue'])
    })
  }

  getSecondTreatment(thatValue) {
    if(thatValue >= 100){
     this.subscriptionTwo = this.myService.sendToBackend(thatValue).subscribe((response)=>{}
    }
  }

MyService.ts

sendToBackend(thatValue){
    let newValue = someFormatingnMethod(thatValue)
    return this.httpClient.post(url , newValue );
}

我的目的是如何动态关闭 subscribtionTwo ,这样,每次我从主题获取新数据后,它就不会被调用n次。

注意: mySubject甚至可以在销毁组件之前注意到一些新数据

我尝试使用switchMap,但似乎无法正常工作

建议?

1 个答案:

答案 0 :(得分:2)

  • 您从一个可观察的开始
  • 该可观察对象发出值后仍保持打开状态,因此我们需要退订
  • 然后您要根据第一个可观察的结果有条件地运行第二个可观察的

我会采用这种方法:

  • 设置您当前正在执行的第一个观测值
  • 使用takeUntil取消销毁
  • 使用filter仅根据条件继续
  • 使用switchMap运行第二个可观察的
  • 第二个可观察的对象是一个HttpClient请求,该请求会自动完成,因此我们不需要退订
private destroyed$ = new Subject();

ngOnInit() {
  getFirstTreatment();
}

ngOnDestroy() {
  this.destroyed$.next();
  this.destroyed$.complete();
}

getFirstTreatment() {
  this.myService.subjectOne.pipe(
    takeUntil(this.destroyed$),
    tap(data => this.myValue = data['myValue']),    
    filter(data => data['myValue'] >= 100),
    switchMap(data => this.getSecondTreatment(data['myValue']))
  ).subscribe(data => {
    console.log(data); // the output of the second observable    
  });
}

getSecondTreatment(myValue): Observable<any> {
  return this.getSecondTreatment(myValue);
}