Executing multiple service calls in Angular2

Is there a way to optimize the number of requests made to a service? I need to retrieve data from my database in batches of 1000 entries each time. Currently, I have a loop set up like this:

while (!done) { ... }

This approach results in unnecessary requests being sent to the database. Is there a better way to efficiently fetch all the required data?

Here is the method defined in my component.ts:

lazyLoadData(): void {

    this.getUntil += 1000;
    if (this.getUntil > this.totalEntries) {
        this.getUntil = this.totalEntries;
    }

    this.salesService.GetEDISalesReportDetailListLazy(this.id, this.getFrom, this.getUntil)
        .then(data => {
            if(this.dataTable == null) {
                this.dataTable = [];
                this.dataTable = data;
                this.isDataTableAvailable = true;
                this.status = this.dataTable.aaData[0].Status;
            } else {
                for(let i = 0; i< data.aaData.length; i++){
                    this.dataTable.aaData.push(data.aaData[i]);
                }
                this.getFrom = this.getUntil;
            }

    });
}

And here is the implementation in my service.ts:

GetEDISalesReportDetailListLazy(id: number, startFrom: number, until: number): any {
return this.http2.post(SERVICE_URL + 'Sales/GetEDISalesReportDetailListLazy', { id: id, startFrom: startFrom, until: until }, this.options)
  .toPromise()
  .then(response => {
    return response.json().ReturnStatus.ReturnObject;
  })
  .catch(this.handleError);

}

If you have any suggestions on how to improve this process, I would greatly appreciate it. Thank you for your assistance.

Answer №1

If you are looking to execute a series of asynchronous operations that return Promises sequentially, there are several approaches to consider.

One of the most elegant and easy-to-read methods is to create an async function with a loop and utilize the await keyword within it like this:

async function fetchData(n) {
  for (let i = 0; i < n; i += 1) {
    const response = await fetch('api/items?page=' + i);
  }
}

While it's possible to achieve the same result without using async/await syntax, this scenario is well-suited for its use.

Without the syntactic sugar, an alternative implementation could look like this:

function fetchData(n) {
  for (let i = 0, p = Promise.resolve(); i < n; i += 1) {
    p = p.then(() => fetch('api/items?page=' + i));
  }
  return p;
}

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

Using Angular's CanDeactivateGuard with Child Components in Angular4

Ensuring user awareness of unsaved changes when navigating away from a page is crucial. Previously, I achieved this in angular 1 using the ng-unsaved changes plugin. However, in angular 4, it seems recommended to utilize the canDeactivate feature. This wor ...

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Issue with loading the schema in the angular.json configuration file

Encountering an issue within the angular.json file that needs attention. { "resource": "/e:/P dev/project/Resume_generator/front/angular.json", "owner": "_generated_diagnostic_collection_name_#1", "c ...

Typescript service wrapper class returning Axios HEAD request

I am attempting to retrieve the header response using a custom Axios HTTP service wrapper. axiosClass.ts import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"; class Http { private instance: AxiosInstance | null = n ...

Developing advanced generic functions in Typescript

I am currently working on a Hash Table implementation in Typescript with two separate functions, one to retrieve all keys and another to retrieve all values. Here is the code snippet I have so far: public values() { let values = new Array<T>() ...

Converting a cast method into a function in Typescript

With some experimenting on WebRTC, I found that the ondatachannel callback takes a function, but I'm wondering if it's possible to use a method of a Typescript class instead. Can someone please assist me with this? export class MainComponent imp ...

How can variables within nested ngFor loops be referenced in Angular 1.5 compared to Angular 10?

This particular piece of code was functional in Angular 1.5. It featured a condition where the <tr> element would only be displayed if the 'showFields' flag for that specific row key was set to true. <table> <ng-container *ngIf=& ...

ERROR: PipeError - Conversion of "Invalid Date" to a date is not possible for the DatePipe

While attempting to format a date with time, I ran into an error. The way I am sending the request is as follows: created = this.datePipe.transform(dateCreated, 'yyyy-MM-ddTHH:mm'); I require the time in order to consume a service that necessi ...

Encountering a glitch while integrating the angular-select2 module into an Ionic 3 application

Attempting to integrate the angular-select2 npm module into my ionic 3 app. Successfully installed the module using npm within my project Imported the package into my app.module.ts file Added <select2> tags into the html file of my application Enc ...

Issue with blueprintjs/core type in JupyterLab Extension after running npm install

Developed a JLab extension and saved it to Git repository. Established a new environment and successfully pulled the code, which was also verified by a friend. Subsequently, included a new react object to the extension and pushed it back to Git in a fresh ...

Encountering an issue while compiling with TypeScript, where a typescript class that involves Meteor and Mongo is throwing an error stating "Property 'Collection' does not exist on type 'typeof Mongo'."

During the compilation of Meteor, an error in the console states "Property 'Collection' does not exist on type 'typeof Mongo'." I'm curious if anyone has encountered this issue before and how they resolved it. I am working with me ...

Using TypeScript with React and Redux to create actions that return promises

Within my React application, I prefer to abstract the Redux implementation from the View logic by encapsulating it in its own package, which I refer to as the SDK package. From this SDK package, I export a set of React Hooks so that any client can easily u ...

Utilizing Angular RouterLink queryParamsHandling for managing optional parameters

Is there a proper way to combine the existing optional queryParams with an additional optional queryParam while linking in the template? Current URL: /search;brand=Trek Preferred link destination: /search;brand=Trek;start=1 (incrementing startCount) I a ...

Discover the power of debugging Typescript in Visual Studio Code with Gulp integration

I've been working on setting up an express/typescript/gulp application, and while it's functional, I'm struggling to debug it using source-maps. Here is how I've set it up: Gulp File var gulp = require('gulp'), nodemon ...

Cross-Origin Resource Sharing Problem - Angular version 8 with NodeJS and ExpressJS

I've attempted various solutions from different sources and have a feeling that I may be overlooking something minor here. In my setup, I have an AngularJS 8 application running on Node 10 with ExpressJS. The specific issue I'm encountering rela ...

Wait for a minimum of X milliseconds using RxJS

I'm attempting to achieve a specific functionality using RxJS: Trigger an event Make an API call Upon receiving the API response, do one of the following: Wait for at least X milliseconds after triggering the event If X milliseconds have already p ...

Is it feasible to set an empty object as the initial default value in the state of a React component?

In my React application with TypeScript, I am using "react": "^17.0.0". Here is how I define the app state: export interface IRoleState { data: API.RoleItem, menus: API.MenuItem, } When I set up the initial state like this: con ...

Utilizing PrimeNG radio buttons for selecting multiple items simultaneously

While dynamically creating multiple radio buttons using *ngFor, I am facing an issue where I can select multiple items from the UI. Below is my code snippet: <div class="p-col-12"> <p>Question Type</p> <div *ngFor ...

How come the CSS for my angular ngx-mat-datetime-picker and mat-datepicker collide when they are both present on the same page?

Within the same form, I have two input fields stacked under each other. One is an ngx-mat-datetime-picker and the other is a mat-datepicker. Individually, they function correctly. However, when I open them for the second time, the one I opened first appear ...

What is the best way to retrieve the chosen item within a Tabmenu component in Primeng?

I have created a simple array of MenuItem objects to populate the Tabmenu component from Primeng. Here is an example: .ts file: items = MenuItem[]; activeItem = MenuItem; //constructor, etc... ngOnInit() { this.items = [ {label: &a ...