How to implement While loop inside RXJS subscription in my angular code

772 views
Skip to first unread message

rj

unread,
Feb 3, 2020, 7:19:56 PM2/3/20
to Angular and AngularJS discussion
I have an Angular code where in i am trying to subscribe to my 1st api and implementing a while loop inside this subscription. Further i need to subscribe to another api inside the while loop. Reason --> I need to subscribe to the inner api multiple times and the while loop should end based on a flag returned by inner api. I tried implementing the below but its not working. Need some help.

```
CallBanyanToFetchQuotes() {

    this.http.post(url1, payload)
      .subscribe(importForQuoteResponse => {
        this.importForQuoteResponse = importForQuoteResponse;
        console.log('LoadID = ' + this.importForQuoteResponse.Load.Loadinfo.LoadID);
        this.loadId = this.importForQuoteResponse.Load.Loadinfo.LoadID;

        while (!this.ratingCompleted) {

          this.http.post(url2, payload)
            .subscribe(getQuoteResponse => {
              this.getQuoteResponse = getQuoteResponse;
              if (this.getQuoteResponse.RatingCompleted === true) {
                this.ratingCompleted = true;
              }
            });
        }
      });
  }
```

Sander Elias

unread,
Feb 4, 2020, 3:39:47 AM2/4/20
to Angular and AngularJS discussion
Hi Rj,

I don't have the time right now to rewrite your code. However, subscribing inside a subscribe is a big antipattern and should be avoided.
What you need is to make it a rxjs flow that uses composition.
the following is just a idea, not working code:

function demo() {
const url1 = '';
const payload = '';
const getQuote = () =>
this.http.post(url2, payload).pipe(
tap(getQuoteResponse => {
this.getQuoteResponse = getQuoteResponse;
if (this.getQuoteResponse.RatingCompleted === true) {
this.ratingCompleted = true;
}
})
);

const sub = this.http
.post(url1, payload)
.pipe(
tap(importForQuoteResponse => {
this.importForQuoteResponse = importForQuoteResponse;
this.loadId = this.importForQuoteResponse.Load.Loadinfo.LoadID;
}),
expand(() => (this.this.ratingCompleted ? empty() : getQuote()))
)
.subscribe();
}

Note, `tap` descibes a side-effect, you should limit those to a minimum to create maintainable code
Reply all
Reply to author
Forward
0 new messages