使服务可观察,直到收到来自其他可观察的响应-角度9

问题描述 投票:0回答:1

我有一个父子组件方案。在父组件上单击按钮时,我正在调用以下函数:

public goNextStep() {
   this.fetchAttributes.emit(new FetchAttributesEvent("myComponent", param));//calls api and get data
    this._stateService.updateStep(2); // just update step number and go to next
  }

在子组件中,我对这两个都有可观察的实现,如下所示:

export class ChildComponent implements OnInit{

    attributes: any[];
    ngOnInit() {
           this._stateService.attributesDataInjector$
           .subscribe(
           attributesData => {

          if (attributesData != null) {
            //live data
            this.attributes = JSON.parse(attributesData);
          }
        }
      )

      this._stateService.stepUpdator$
      .subscribe(
        newStep => {
       // Use this.attributes value;
       }
     )
   }
}

现在,我的问题是,因为emit()调用外部服务并获取数据,这需要时间,而更新步骤只是本地操作,因此它会很快发生。因此,stepUpdator $操作首先完成,并尝试使用this.attributes,由于api调用仍在进行中,因此当前为空。结果,这里出现未定义的错误,处理继续进行。稍后,服务调用完成,attributesDataInjector $初始化this.attributes。

我想以某种方式等待直到由attributeDataInjector $初始化this.attributes,然后处理stepUpdator $(类似promise的事情),但是我无法做到这一点。有线索吗?

observable angular-promise angular-services angular9 emit
1个回答
0
投票

您可以使用skipUntil rxjs运算符来实现该功能。它对两个可观察值起作用,并防止第一个值可观察到第二个值发出该值。有关更多信息,您可以阅读this

© www.soinside.com 2019 - 2024. All rights reserved.