Tips for efficiently loading data in a sequence using rxjs: within each sequence, there could be multiple calls made

const dates = [{start:'03/06/2020', end: '03/09/2020'}, {start:'03/12/2020', end: '03/03/2021'}, ...]

const fetchData =  service.get(page = 1, dates[0]) and service.get(page = 2, dates[0]) 
retrieves the necessary data, but considering multiple pages might be involved. Each page's data must be collected before moving on to the next date.

data.subscribe(resp=> somesubject.next(this.values = this.values.concat(resp)))
'resp' represents the result of each API call. The values for each date are merged together on the client side.

What would be the most effective approach to manage this situation? Feel free to ask if you need further clarification.

Answer №1

Assuming the following initial conditions / assumptions:

  • dates represents an array of date intervals to facilitate data querying.
  • PageResponse is a response type from the api service, containing the current page number and returned items.
  • getPage is a method that returns an Observable<Response> for a specific date range and page number (starting from 0). When there are no more results, the response includes an empty array of items.
  export type PageResponse = {
    page: number;
    items: any[];
  };
  getPage(dateInterval: any, page: number): Observable<Response> {
    // use dateInterval to query expected data...
    // or call service.get...
    return this.http.get<PageResponse>(`http://.../pages/${page}`);
  }

You can implement

from(dates)
      .pipe(
        concatMap(dateInterval =>
          this.getPage(dateInterval, 0).pipe(
            expand(response => {
              if (response.items?.length) {
                return this.getPage(dateInterval, response.page + 1);
              } else {
                return EMPTY;
              }
            }),
            map((page) => page.results)
          )
        ),
        mergeAll(),
        toArray()
      )
      .subscribe(results => {
         // results is a flat array of all items returned
         ...
      });

This code serves as an illustration and should be customized to fit your specific scenario. Some types may be omitted (such as items), but this is to simplify the example.

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

There are no properties shared between type 'dateStyle: string' and type 'DateTimeFormatOptions'

"typescript": "^4.0.3" Can anyone help me resolve the TypeScript error I am encountering in the code below?: components/OrderListItem.tsx const newedate = (_date) => { const options = {dateStyle: 'medium'}; //{ weekday: ...

Verify user using Cognito user pool log-in information

Is it possible to authenticate a user using only user pool credentials without an identity pool/IdentityPoolId? Check out this link for more information: https://github.com/aws/amazon-cognito-identity-js The example provided in the link above specifically ...

Tips for transferring state information from a client to a server component within Nextjs?

Currently, I am working on a project where I need to read and write data from a locally stored .xml file that contains multiple <user> tags. The technology stack includes TypeScript and NextJS. The project is divided into three main components sprea ...

Create an observable array that contains both outer and inner response properties within an Angular application

How can I create an Observable array in Angular by making API calls based on the response of another API call, which returns an array of elements? For example: queryThatReturnsArray().pipe( switchMap((outerResponse) => { return forkJoin(out ...

"Passing Data from Angular Parent Component to Child Component

At first, the parent component and child don't have any connection. It's just a list of elements. However, when the user clicks on the list, the child component is loaded. Then, I can call a method of the child component from the parent using @Vi ...

Unable to locate the module from my personal library in Typescript

The Query Why is my ng2-orm package not importing or being recognized by vscode when I try to import Config from 'ng2-orm'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser&a ...

The error message "localStorage is undefined in Angular Universal" indicates that the local

I have chosen to utilize universal-starter as the foundation of my project. Upon initialization, my application reads a token containing user information from localStorage. @Injectable() export class UserService { foo() {} bar() {} loadCurrentUse ...

Make sure to include a warning in the renderItem prop of your Flashlist component

I have encountered a type warning in my React Native application. The warning is related to the renderItem prop of FlashList. How can I resolve this issue? Warning: Type 'import("/Users/mac/Desktop/project/pokeApp/node_modules/@react-native/vi ...

Struggling to refine the result set using jsonpath-plus

Utilizing the jsonpath-plus module (typescript), I am currently working on navigating to a specific object within a json document. The target object is nested several levels deep, requiring passage through 2 levels of arrays. When using the following jsonp ...

Unable to open modal externally without encountering an error in MaterializeCSS

I'm currently facing an issue with a standard modal that pops up at the bottom of the page. I have a function that generates multiple components on the page, each with a 'play' button. When this button is clicked, it triggers a function pass ...

Finding the solution to the perplexing issue with Generic in TypeScript

I recently encountered a TypeScript function that utilizes Generics. function task<T>(builder: (props: { propsA: number }, option: T) => void) { return { run: (option: T) => {}, } } However, when I actually use this function, the Gener ...

What is the best method for compressing and decompressing JSON data using PHP?

Just to clarify, I am not attempting to compress in PHP but rather on the client side, and then decompress in PHP. My goal is to compress a JSON array that includes 5 base64 images and some text before sending it to my PHP API. I have experimented with l ...

Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function. For example: interface employee { first: st ...

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

I'm facing issues with Angular commands not functioning properly even after installing the Angular CLI and configuring the

Every time I attempt to create a new project using Angular CLI by typing: ng n app I encounter the following error message: C:\Users\Venkateshwarn M\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng: ...

What purpose does the array.pop()!(object) syntax serve within Codemirror?

Within the Codemirror 6 documentation and at line 41 of the code, there is a snippet that reads: while (pending.length) pending.pop()!(data.updates) I'm curious about the meaning of this syntax. It appears to be TypeScript specific. How would this lo ...

Error in Template Syntax for External Pug Templates: Component template must have a root element, not just plain text

I've been struggling to make Pug templates work with Vue class-based components using a separate file for the pug template. The documentation suggests that adding this code should do the trick: // webpack.config.js -> module.rules { test: /&bsol ...

"Exploring the Power of Angular 2 with Route Resolving

Currently, I am diving into the world of Angular and it's all quite new to me. I have a challenge where I need to display data in a view fetched from the server asynchronously. To tackle this, I attempted to use resolves to ensure the data is retrieve ...

A guide on transforming JSON data to an array format where nested arrays are encapsulated within objects using curly braces instead of square brackets in TypeScript

Retrieve data from a REST API in the following format: { "ProductID":1, "Category":[ { "CategoryID":1, "SubCategory":[ { "SubCategoryID":1, } ] } ] } I need to t ...

Angular: encountering template parse errors with unknown <component> element

I'm struggling to import a component into another component, but the imported component cannot be found. Here is the error message: Uncaught Error: Template parse errors: 'aktenkorrespondenzenTemplate' is not a known element: 1. If 'ak ...