繁体   English   中英

如何在构造函数中阻止订阅调用直到完成?

[英]How to block a subscription call in constructor until completed?

如何阻止构造函数以等待 Http 调用返回数据?

constructor() {
  this.initRestData().subscribe();
  // wait for data to be read
  this.nextStep();
}

应用程序中的其他服务/组件需要通过 initRestData() 调用检索到的数据。 我只需要在启动时执行此操作。 如果有更好的方法来处理这个问题,那么 Observable 也可以。

您可以在subscribedo -operator 中链接调用:

constructor() {
  this.initRestData()
    .do(receivedData => this.nextStep(receivedData)})
    .subscribe();
}

对于其他服务也依赖this.nextStep() ,您也应该将其实现为流:

private initialData$ = new BehaviorSubject<any>(null);
constructor() {
  this.initRestData()
    .do(data => this.initialData$.next(data))
    .switchMap(() => this.nextStep())
    .subscribe();
}

nextStep(): Observable<any> {
    return this.initialData$
        .filter(data => data != null)
        .take(1)
        .map(data => {
            // do the logic of "nextStep"
            // and return the result
        });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM