【问题标题】:Make service observable wait until receives response from other observable - angular 9使服务可观察等待直到收到来自其他可观察的响应 - 角度 9
【发布时间】:2020-05-25 14:06:06
【问题描述】:

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

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 调用仍在进行中。结果,我在这里得到了 undefied 的错误,并且处理继续进行。稍后,服务调用完成,attributesDataInjector$ 初始化 this.attributes。

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

【问题讨论】:

    标签: observable angular-promise angular-services angular9 emit


    【解决方案1】:

    您可以使用skipUntil rxjs 运算符来实现该功能。它适用于两个 observables 并防止值从第一个 observable 直到第二个 observable 发出值。更多信息可以阅读this

    对于您的场景:

    import { skipUntil } from 'rxjs/operators';
    
    this._stateService.stepUpdator$
      .pipe(skipUntil(this._stateService.attributesDataInjector$))
      .subscribe(newStep => {})
    

    【讨论】:

      猜你喜欢
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 2018-01-03
      • 1970-01-01
      • 2019-03-24
      相关资源
      最近更新 更多