Building an Angular CLI application with Typescript that handles multiple HTTP calls using polling through a timer

I am working with a Django backend and I need to check the status of multiple Celery Tasks () every 3 seconds.

For instance, let's say I have 4 task IDs:

  1. 3099023
  2. 3493494
  3. 4309349
  4. 5498458

My goal is to make an http.get<...>(backend) call every 3 seconds for each ID until the state of the task is "FINISHED." The polling should stop once a task is finished.

Is there a straightforward way to accomplish this?

I attempted to implement this using a for loop:

  1. Iterate through the list of IDs
  2. Create a timer for each individual ID
  3. Poll the status of the ID by making an HTTP call to the backend within each timer
  4. Continue polling if the response indicates that the task is not yet finished, otherwise stop polling

Answer №1

I believe that leveraging rxjs can enhance our solution, as demonstrated in this example showcasing the use of rxjs operators to meet your objective.

PLEASE NOTE: This example simplifies things by excluding Components/Services.

import { interval, of, mergeMap, from, switchMap, takeWhile } from 'rxjs';


const ids = [3099023, 3493494, 4309349, 5498458];

from(ids).pipe(
  mergeMap((id) => 
    interval(3000).pipe(
      switchMap((val) => mockHttpCallExample(val, id)),
      takeWhile((httpResonse) => httpResonse !== 'FINISHED')
  ))).subscribe(val => console.log(val))


const mockHttpCallExample = (val, id) => {
  let httpResponse;

  if (id % 2 === 0 && val === 4) {
    httpResponse = 'FINISHED'
  } else if (id % 2 !== 0 && val === 5) {
    httpResponse = 'FINISHED'
  } else {
    httpResponse = 'OK'
  }

  console.log(id, val);

  return of(httpResponse)
} 

What's Happening Here:

  1. The from operator emits a value for each id
  2. In the mergeMap, an http request is made to the API every 3 seconds
  3. The process concludes upon receiving the 'FINISHED' string from the mock API call

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

Removing feedback on a particular blog entry

I'm struggling to remove all comments associated with a specific blog post that is about to be deleted using mongoose. I can't figure out why my code isn't functioning correctly. const commentSchema = new mongoose.Schema({ message: { type ...

What is the process for utilizing the TypeScript compiler with nodejs?

I have a sample code saved in a file called hello.ts Upon the completion of nodejs setup on Windows, execute the following command to install typescript: npm install -g typescript Is there a way to compile hello.ts directly with node.js? While using "T ...

When using an Angular client to send a request with an access token to Azure AD WebAPI, the response may still show

I have been facing an issue with my Angular client while trying to authenticate and receive a token from Azure AD. Despite adding the token to the header and calling the WebAPI, I keep encountering the message: "Authorization has been denied for this requ ...

There is no valid injection token found for the parameter 'functions' in the class 'TodosComponent'

While working in my code, I decided to use 'firebase' instead of '@angular/fire'. However, I encountered an issue that displayed the following error message: No suitable injection token for parameter 'functions' of class &apos ...

TypeScript excels in typechecking when using two individual assignments, but may encounter issues when attempting typechecking with tuple

I am quite puzzled by a discovery I made and I am seeking to understand why TypeScript is displaying this behavior and what the underlying reason may be. Here is the code snippet: class A { constructor(public name : String, public x = 0, public y = 0) ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

Refresh the display after adding an item to an array in Angular

Currently, I am facing an issue with updating the view based on adding an item to an array of objects through a click handler. While the item is successfully pushed into the array, it does not reflect in the view. I am wondering if placing the method withi ...

What's the best way to use the keyboard's enter key to mark my to-do list

I'm looking to update my todo list functionality so that pressing enter adds a new todo item, instead of having to click the button. <h1 style="text-align:center">Todo List</h1> <div class="container"> ...

Utilizing AES encryption in C# and decrypting it in Angular, converting it from a byte[] / number array with the help

I am looking to securely encrypt and decrypt a byte[] in a C# API endpoint, then convert the decrypted document to base64 for viewing in a PDF viewer within an Angular 14 app. I came across this helpful guide on Stack Overflow [https://stackoverflow.com/q ...

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

Exploring the versatility of Vue.js through props and scoped slots

Coming from a React background, I am used to being able to easily alter children components before they render. However, after spending hours reading the VueJS documentation and searching forums, I have not been able to find a straightforward way to do thi ...

Tips for effectively transmitting data while utilizing a declarative/reactive data access method with RxJS in Angular?

Angular typically follows a classic pattern for data access that looks like this: Traditional Data Access Pattern getProducts(): Observable<Product[]> { return this.http.get<Product[]>(this.productsUrl) .pipe( tap(data => consol ...

Guide to dynamically load external JavaScript script in Angular 2 during runtime

Currently, I am integrating Twitter digits for authentication purposes. To implement this feature, a small .js script needs to be downloaded and initialized. The recommended approach is to directly fetch the file from the Twitter server. In order to succe ...

Having trouble with react-i18next not working properly in my React Native application

I recently initiated a new react-native project, but I seem to be encountering an issue with my react-i18next translations. Despite having the keys correctly set up, I am unable to view the translations. Furthermore, I have noticed that my components are ...

Global.styles.css not applying background-color in Angular

I decided to enhance the appearance of my website by adding some code to the global styles.css file in order to change the background color to light blue. html, body{ background-color: lightblue ; } However, after refreshing the home.component page, I n ...

Establishing global date restrictions for the DatePicker component in Angular 8 using TypeScript across the entire application

I am currently learning Angular 8 and I am looking to globally set the minimum and maximum dates for a datepicker in my application. I would like to accomplish this by using format-datepicker.ts. Any suggestions on how I can achieve this? Min date: Jan 1, ...

Angular2 RC definitions are not recognized by tsc

Currently, I am utilizing angular version 2.0.0-rc.1, however, I am encountering issues with the typescript compiler (Typescript version 1.8.10). Whenever I run tsc on my project, I am bombarded with numerous errors similar to this one: app/app.componen ...

Challenge your TypeScript skills: convert snake_case to camelCase and back again

I am looking to develop a Typescript function that can deeply traverse a plain object and convert all snake_case keys to camelCase. Additionally, I need a function that can convert camelCase keys to snake_case throughout the object. While implementing thi ...

Steps to extract key and value from a collection in Firebase database

In my Firebase database, I have a specific structure that I need to retrieve and display using ngFor in my view. However, I also need access to the unique key generated by Firebase when using the push method for each object. https://i.sstatic.net/nR2nK.pn ...

Understanding the significance of the add() operator in RxJS

Can someone clarify the purpose of the add() operator in rxjs? I've seen it mentioned that it includes a teardown function, but there isn't much detail on what exactly a teardown is or why it's necessary. My specific query relates to impleme ...