Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

angular - Waiting for an observable to finish

I have a method that needs to wait for an observable to finish. I know observable are great for returning single pieces of data over time but I need to know when this observable has completely finished returning all of its data so I can run validation code on the object it has returned.

The method getCustom subscribes to an observable run on the supplied url which then returns the observable.

I am not too sure if this is the best way to approach this situation so I would appreciate if anyone could give me any advice or a direction to handle this.

  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
    });

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...