等待 observable 完成

Waiting for an observable to finish

我有一个方法需要等待 observable 完成。我知道 observable 非常适合随着时间的推移返回单条数据,但我需要知道这个 observable 何时完全返回其所有数据,以便我可以 运行 在它返回的对象上验证代码。

getCustom 方法在提供的 url 上订阅一个可观察对象 运行,然后 returns 可观察对象。

我不太确定这是否是解决这种情况的最佳方法,所以如果有人能给我任何建议或指导来处理这个问题,我将不胜感激。

  private validateQuoteRetrievalAnswers(reference: string) {

         // Get the risk from the server
        this.riskManager.getRiskFromServer(reference);

        if (this.riskManager.risk) {
            // Validate risk that was returned
        }
    }
getRiskFromServer(quoteReference: string) {

    this.riskService.getCustom("Url").subscribe => {
        // need to know when the observable has returned the risk
    });

}

我将如何应对这一挑战:

查询你的后端,当我们得到我们需要的东西时将它推送到一个主题

riskSubject = new Subject<Risk>();

getRiskFromServer(quoteReference: string) {
  this.riskService.getCustom("Url")
  .subscribe( 
    data => { this.riskSubject.next(data); },
    error => { console.log(error) }
 });
}

然后订阅主题,等到你得到你需要的并开始验证

private validateQuoteRetrievalAnswers(reference: string) {

         // Get the risk from the server
        this.riskManager.getRiskFromServer(reference);
        // subscribe to subject
        this.riskManager.riskSubject.subscribe(
         data => {
           //do your validation
        })
}

The heart of an observable data service is the RxJs Subject. Subjects implement both the Observer and the Observable interfaces, meaning that we can use them to both emit values and register subscriptors.

The subject is nothing more than a traditional event bus, but much more powerful as it provides all the RxJs functional operators with it. But at its heart, we simply use it to subscribe just like a regular observable

来源:angular-university.io

或者你可以使用 Observable.fromPromise(promise) 但如果你是 ng2 的新手,这会让事情变得更难理解