Waiting for an observable to finish

一笑奈何 提交于 2019-12-05 05:52:56

how i would tackle this challenge:

Query you back-end and when we've got what we need push it to a Subject

riskSubject = new Subject<Risk>();

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

and then subscribe to subject and wait until you get what you need and start validating

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

source: angular-university.io

OR you can use Observable.fromPromise(promise) but this will make things a bit more complicated to understand if you are new to ng2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!