嵌套订阅,内部订阅取决于外部订阅

时间:2020-06-26 17:41:19

标签: angular typescript asynchronous rxjs observable

我在angular组件中有一个嵌套的订阅。我无法与您共享代码,但是我将尽力解释我所面临的情况。情况就是这样

ParentComponentA

result:any;
mystatus: boolean = false;
@ViewChild(ChildComponentA): childComponentA;

this.myService.getResult().subscribe(res =>{
    
   this.result = res;

   // in the first subscribe there will be a lot of calculations based on res
   /*the second service  will take one of the 
    values as an argument which will be there in res, let's say a flag*/

   this.mySecondService.getStatus(this.result.flag).subscribe(flagSatus => {

    this.myStatus = flagStatus; //flagStatus will return true value

  /*now here I have a function named myFunction, which will use this.results
    values and flagStatus to do some calculation*/

    myFunction(this.res.profile, this.myStatus)
             });
      });

  myFunction(profile, status) {
  /* here childComponentA is coming undefined 
     when I'm printing in it console therefore it is not going in if condition*/
  if(this.childComponentA) {
   }
 }


HTML template A
<div *ngIf="myStatus">
  <! -- child-comp is selector of ChildComponentA -->
   <child-comp> </child-comp>
</div>

现在,一切正常,但是从内部订阅获得的flagStatus,我在html模板中使用它。 childComponentA正在显示,但是当我执行console.log(this.childComponentA)时,它是未定义的。这就是我的确切问题,这可能是因为myStatus的初始值为false。但是,当我将整个内部订阅放入setTimeOut时,一切工作正常,如果myFunction的条件也进入了。

为了避免使用setTimeOut,我想使用rxjs来以有效的方式实现我正在尝试做的事情。我到处都抬起头来,但找不到与我相似的例子。从我发现的结果来看,我们可以使用switchMap来完成我想要的事情。我的问题是我到底该如何使用它,或者我还可以使用其他运算符?请帮助我。

3 个答案:

答案 0 :(得分:0)

您可以使用 mergeMap 订阅多个Observable。

const result1$ = this.myService.getResult();
result1$.pipe(
  mergeMap(res => this.mySecondService.getStatus(res.flag).pipe(flagSatus => {
    this.myFunction(res, status);
  })));

答案 1 :(得分:0)

您可以使用 switchMap ,因为您试图基于另一个可观察对象的另一个结果来获取一个可观察对象的结果。 您可以在此处阅读有关switchMap的更多信息。 https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap

答案 2 :(得分:0)

我已经使用Rxjs主题解决了这个问题,当可观察的完成时,它充当了事件发射器。如果保存上一个值有意义(例如,如果您有一个将在其他服务中使用的ID),则可以使用behaviourSubject。 What is the difference between Subject and BehaviorSubject?

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

 mySubject = new BehaviorSubject(null);

// This would be the first request that loads data
getData() {
return this.http.get<any>(Services, options).map(
  res => {
    console.log('res from service', res);
    this.mySubject.next(res});        
  });
}

现在,如果您有另一个需要此数据且先前已加载的组件,它将仍然可用

this.service.mySubject.subscribe( (res:any) => {
    this.http.get<any>(res.someParam , options).map(
    ....
  });
}
相关问题