Angular 如何使用MergeMap或FlatMap编写下面的代码,或者使用rxJs操作符编写更好的代码?

Angular 如何使用MergeMap或FlatMap编写下面的代码,或者使用rxJs操作符编写更好的代码?,angular,typescript,rxjs,ngrx,rxjs-pipeable-operators,Angular,Typescript,Rxjs,Ngrx,Rxjs Pipeable Operators,我有两个可以观察到的管道。我需要一个接一个地运行,比较两个值是否相等。我尝试了下面的代码。这应该是可行的,当第一个可观察的值发出时,它应该去获取第二个obserbla值,并且应该捕获第一个返回值。我需要一些专家的帮助,以更好的方式重构这段代码 this.selectedUnitDetailModel$.pipe(shareReplayUntil(this.destroySub)).subscribe( (res: UnitDetail) =>{

我有两个可以观察到的管道。我需要一个接一个地运行,比较两个值是否相等。我尝试了下面的代码。这应该是可行的,当第一个可观察的值发出时,它应该去获取第二个obserbla值,并且应该捕获第一个返回值。我需要一些专家的帮助,以更好的方式重构这段代码

   this.selectedUnitDetailModel$.pipe(shareReplayUntil(this.destroySub)).subscribe(
          (res: UnitDetail) =>{
              if(res.unitTwo){
                this.appStore.select(selectUnit).
                pipe(shareReplayUntil(this.destroySub)).subscribe(
                  (unitId: string) => {
                    if(unitId ===  res.unitTwo){
                      this.sameUnit = true;
                    }else{
                      this.sameUnit = false;
                    }
                  });
              }
          }
       );

您不需要高阶运算符,因为可观察对象
this.selectedUnitDetailModel$
this.appStore.select(selectUnit)
彼此独立。相反,您可以使用诸如
forkJoin
combinelatetest
zip
之类的函数来并行地从它们获取通知

您可以在这些函数中找到不同之处

试试下面的方法

forkJoin(

this.selectedUnitDetailModel$.pipe(take(1)),//console.log(error)//Try
this.selectedUnitDetailModel$.pipe(withLatestFrom(this.appStore.select(selectUnit)),map([{unitTwo},unitId])=>unitTwo==unitId),点击(console.table),共享replayuntil(this.destroySub))。订阅(sameUnit=>{this.sameUnit=sameUnit;})
。什么是
shareReplayUntil
?@RafiHenig我创建主题并将所有管道合并到它,当组件销毁时,我将取消订阅该主题。实际上它用于取消订阅Observable。知道了,我会尝试这个。需要知道的一件事是,'this.selectedUnitDetailModel$'这个管道值是更改的,然后它会在第二次工作吗?(想想看,这个。selectedUnitDetailModel$是列表->我将逐个选择项目,然后是否需要重新破解单位等式)@乌玛:不会的。就像我之前说的,对于连续数据流,你可以使用
CombineTest
来代替。我已经更新了答案。请检查更新后的代码是否对你有效。迈克尔,我尝试了第二个code.CombineTest->给出了一些分离声纳问题..,以及行([res:UnitDetail,unitID:string],放置给定的编译错误,如未定义:(@uma:我不确定这个
shareReplayUntil
是如何实现的。请尝试用
takeUntil
操作符替换它。它执行与您要求的相同的操作:当组件被销毁时关闭打开的订阅。我也更新了答案。@uma:还请从数组
([res,unitId])中删除类型定义
。我已经更新了答案。您可以在mergeMap中添加return of(false)来处理
res.unitTwo
为false的场景。
this.selectedUnitDetailModel$.pipe(shareReplayUntil(this.destroySub),mergeMap(
          (res: UnitDetail) =>{
              if(res.unitTwo){
               return this.appStore.select(selectUnit).
                pipe(shareReplayUntil(this.destroySub),map(
                  (unitId: string) =>  unitId ===  res.unitTwo);
              }
          }
       ).subscribe({
        next: (sameUnit: boolean) => {
           //do something 
        }
       });