简体   繁体   English

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

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

How may I block a constructor, to wait for an Http call to return data?如何阻止构造函数以等待 Http 调用返回数据?

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

The data retreived by the initRestData() call is needed by other services/components in the application.应用程序中的其他服务/组件需要通过 initRestData() 调用检索到的数据。 I only have to do this at startup.我只需要在启动时执行此操作。 If there is a better way to handle this then Observable that would be ok too.如果有更好的方法来处理这个问题,那么 Observable 也可以。

You could chain the calls either inside the subscribe or in a do -operator:您可以在subscribedo -operator 中链接调用:

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

For the case that other services rely on this.nextStep() as well, you should implement this as a stream as well:对于其他服务也依赖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