How to integrate a While loop within an RXJS subscription

I have a piece of Angular code where I am attempting to subscribe to my first API and include a while loop within this subscription. Additionally, I need to subscribe to another API inside the while loop. The reason for this is that I need to subscribe to the inner API multiple times and have the while loop terminate based on a flag returned by the inner API. I have tried to implement the code below, but it is not functioning as expected. I am in need of some assistance.

CallBanyanToFetchQuotes() {
    const url1 = 'http://ws.integration.banyantechnology.com/services/api/rest/ImportForQuote';

    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) {
          const url2 = 'http://ws.integration.banyantechnology.com/services/api/rest/GetQuotes';

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

Answer №1

When making a post request using this.http.post with a payload to URL1, the response is then switched and mapped to a different importForQuoteResponse. From there, the LoadID is extracted and stored in loadID. The sequence continues by setting a timer to make periodic calls to URL2 with the same payload. Each response is tapped into to retrieve quote response data. The calls continue until the RatingCompleted flag in the response is true. Once the condition is met, the ratingCompleted flag is set to true.

This scenario is demonstrated in a "fool example" on StackBlitz.

The explanation of the code is that it initially makes a post request but switches the subscription to a timer, which triggers another post request. The timer interval can be adjusted as needed. The code is structured to keep making calls until a specific condition is met in the response.

Answer №2

To replicate a while loop, consider utilizing the expand method. With expand, the input is passed to the destination right away, then mapped to an Observable, and the output becomes the next input in the sequence. To terminate this recursive process, map to EMPTY.

// If the URLs are constant, move them outside the function
const url1 = 'http://ws.integration.banyantechnology.com/services/api/rest/ImportForQuote';
const url2 = 'http://ws.integration.banyantechnology.com/services/api/rest/GetQuotes';

callBanyanToFetchQuotes() {
    this.http.post(url1, payload).pipe(
        // Handle the response from url1
        tap(importForQuoteResponse => {
            this.importForQuoteResponse = importForQuoteResponse;
            console.log('LoadID = ' + this.importForQuoteResponse.Load.Loadinfo.LoadID);
            this.loadId = this.importForQuoteResponse.Load.Loadinfo.LoadID;
        }),
        // Switch to url2 request
        switchMap(_ => this.http.post(url2, payload))
        // Keep executing url2 request until rating is complete or end with EMPTY
        expand(quoteResponse => quoteResponse.RatingCompleted ? EMPTY : this.http.post(url2, payload))
        // Process responses from url2 requests
    ).subscribe(quoteResponse => {
        this.getQuoteResponse = quoteResponse;
        if (quoteResponse.RatingCompleted === true) {
            this.ratingCompleted = true;
        }
    });
}

Using the expand method ensures that the subsequent http call is triggered directly and only after receiving a response from the previous one.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The standard process and organization of a project using AngularJS in conjunction with Python Flask

As someone new to the MV* client-side framework craze, I find myself leaning towards AngularJS over Knockout, Ember, or Backbone. However, I'm unsure about the workflow involved. Should I start by developing a client-side application in AngularJS and ...

Implement the use of NextAuth to save the session during registration by utilizing the email and password

When registering a user using email, password and username and storing in mongodb, I am looking to incorporate Next Auth to store sessions at the time of registration. My goal is to redirect the user in the same way during registration as they would experi ...

Utilizing the variable $this outside of an object context within an Ajax function

Encountering the following error: Fatal error: Uncaught Error: Using $this when not in object context in E:\xampp\htdocs\StudentGuideBook\Version1.0\models\AjaxChecking.php:4 Stack trace: #0 {main} thrown in E:\xampp&b ...

Index.js is dynamically importing a .tsx file post-build, with a specific focus on Windows

While working on my project, I decided to customize a module by cloning it and making some changes. After installing the dependencies and building it, I encountered an error when trying to run it. The error message stated: Error: Unable to resolve module & ...

In the present technological landscape, is it still considered beneficial to place Javascript at the bottom of web pages?

As a beginner in web programming, I've recently delved into Javascript. A hot debate caught my attention - where should javascript be placed, at the top or at the bottom of a webpage? Supporters of placing it at the top argue that a slow loading time ...

SOLVED: NextJS restricts plugins from modifying HTML to avoid unnecessary re-rendering

My current scenario is as follows: I am in the process of developing a website using NextJS (SSR) I have a requirement to load a script that will locate a div element and insert some HTML content (scripts and iframes) within it. The issue at hand: It se ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

How to Resolve File Paths in CSS Using Angular 7 CLI

My assets folder contains an image named toolbar-bg.svg, and I am attempting to use it as the background image for an element. When I use background: url('assets/toolbar-bg.svg'), the build fails because postcss is unable to resolve the file. How ...

Uncovering the Solution: Digging into a Nested ng-repeat to Access an Array in AngularJS

I am working with a recursive array in JavaScript: [{ type: 'cond', conditionId: 1, conditions: undefined }, { type: 'cond', conditionId: 2, conditions: undefined }, { type: 'group', conditionId: undefined, ...

Reactjs and Redux encounter an Unhandled Rejection with the error message stating "TypeError: Cannot read property 'data' of undefined"

Encountering an error while implementing authentication with react + redux. When attempting to register a user in the redux actions using async / await, I consistently receive this error within the catch block. Here is the snippet of the actions code: imp ...

Navigating Google Oauth - Optimal User Sign in Locations on Frontend and Backend Platforms

What are the distinctions between utilizing Google OAuth versus implementing user sign-ins at the frontend of an application, as opposed to handling them on the backend? For instance, managing user authentication in React to obtain the ID and auth object ...

Is it possible to have nullable foreign keys using objectionjs/knex?

It seems like I'm facing a simple issue, but I can't quite figure out what mistake I'm making here. I have a table that displays all the different states: static get jsonSchema() { return { type: 'object', propert ...

Exploring the process of retrieving token expiration in TypeScript using the 'jsonwebtoken' library

Currently utilizing jsonwebtoken for token decoding purposes and attempting to retrieve the expiration date. Encountering TypeScript errors related to the exp property, unsure of the solution: import jwt from 'jsonwebtoken' const tokenBase64 = ...

The checkbox click function is not functioning properly when placed within a clickable column

In my coding project, I decided to create a table with checkboxes in each column. <table class="bordered"> <thead> <tr style="cursor:pointer" id="tableheading" > <th>Name ...

`Turn a photo into a circular shape by cropping it`

Even though I know that the solution involves using border-radius: 50%, it doesn't seem to be working for my situation. In my code using React/JSX notation, this is how the icon is displayed: <i style={{ borderRadius: '50%' }} className= ...

Is the side tab overflowing the window due to its absolute positioning?

My browser window has a side tab that slides in when clicked using jQuery. The issue I'm facing is that the tab overflows the body due to its absolute positioning. However, the overflow stops when the tab is pulled in by jQuery. It only happens when t ...

Updating the Navigation Bar and Theme in CRM Dynamics 2013 to Reflect Your Organization's Branding

In my CRM Dynamics 2013 setup, I am faced with a unique challenge. I need to customize the Organization navigation bar based on which organization is currently loaded. Specifically, I have two organizations - QA and PROD. When a user switches to the QA org ...

Looping through a series of URLs in AngularJS and performing an $

Currently, I am facing an issue while using angular.js with a C# web service. My requirement is to increment ng-repeat item by item in order to display updated data to the user. To achieve this, I attempted to utilize $http.get within a loop to refresh t ...

I'm having trouble extracting data into my HTML file using the append function in Jquery. What could be causing this issue?

Hey there, I'm having some trouble extracting data from a URL to my HTML file using jQuery. Can anyone help out? I'm still new to this. Here's the code <html> <head> <title> My Program </title> <script src="ht ...