Managing individual HTTP responses within Angular 6

I currently have 15 HTTP requests being sent to the API individually. Instead of waiting for all requests to finish processing (especially one that can take a few minutes), I want to handle responses as they come in.

On the service side:

    findOneByOne(): Observable<any> {
    const calls = this.getCardsPath().map(el => this.getPromises(el));
    return Observable.forkJoin(calls)
        .map(res => {
            const tab = [];
            for (let i = 0; i < res.length; i++) {
                tab.push(this.checkInfoService(res[i].json()));
            }
            return tab;
        });
}


getPromises(str: String): Promise<any> {
    return this.requester.obtain({
        restUrl: "/administration/" + str,
        method: RequestMethod.Get
    })
        .toPromise()
        .then(res => res)
        .catch(err => err);
}

On the component side:

    displayDashboardInfoService() {
    if (this.featuresFlag.getCurrentVersion() !== "1.08" && this.featuresFlag.getCurrentVersion() !== "-1") {
        this.busy = this.dashboardInfoService.findAll()
            .then((res: DashboardInfo[]) => this.findPaths(res))
            .then((res: DashboardInfo[]) => this.loadItems(res))
            .catch((err: any) => {
                if (environment.debugLevel >= 3) console.error(err);
            });
    }
    else {

        this.dashboardInfoService.findOneByOne()
            .subscribe((res) => {
                const tab = [];
                for (let i = 0; i < res.length; i++) {
                    tab.push(res[i][0]);
                }
                this.findPaths(tab);
                this.loadItems(tab);
            });
    }

}

Thank you :)

Answer №1

If you want to receive an event after each request is complete instead of waiting for all requests to finish, one solution is to replace the forkJoin with merge.

For example, consider this code snippet:

waitForAll() {
  this.values = [];
  this.loadAllAtOnce([100, 200, 300, 400, 3000])
    .subscribe(values => {
      this.values = values;
    });
}

loadAllAtOnce(values: number[]) {
  return forkJoin(
    values.map(x => of (x).pipe(delay(x)))
  ).pipe(
    tap(values => {
      console.log(values);
    })
  );
}

You can rewrite it like this:

asTheyCome() {
  this.values = [];
  this.loadAsSoonAsAvailable([100, 200, 300, 400, 3000])
    .subscribe(value => {
      this.values.push(value);
    });
}

loadAsSoonAsAvailable(values: number[]) {
  return merge(
    ...values.map(x => of (x).pipe(delay(x)))
  ).pipe(
    tap(value => console.log(value))
  );
}

Check out a live demonstration here.

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

What could be the reason for the function providing the value of just the initial input?

Why am I only getting "White" when I click on the colors? I can't seem to get any other values to appear on the screen. I'm confused about what mistake I might be making here. var x = document.getElementById("mySelect").value; function myFunc ...

Creating a static Top Bar that remains unaffected by page refreshing using Ajax or any other method can be achieved by implementing JavaScript and CSS

I've designed a sleek top bar for my upcoming website project. Below is the CSS code snippet for creating this clean div bar: .topbar { display:block; width:100%; height:40px; background-color:#f5f5f5; } I'm looking to incorporate a simple .SWF ...

What is the most effective way to choose and give focus to an input using JavaScript or jQuery?

How do you use JavaScript or jQuery to focus on and select an input? This is the relevant snippet of my code: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </he ...

Utilizing a callback function to update the value of a variable that is declared outside of the getJSON function

I'm currently facing an issue with this function I have. function customCheck(username){ var result = "normal"; $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){ if(data.stream == null) re ...

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

Executing a Javascript function post AJAX page loading

I'm not a coding expert, so I hope my question is still clear. Essentially, I have an index.php page with filters (by project, year, month) that send variables to filterData.php after clicking submit. These variables are then used in SQL statements t ...

Error always appears when using addMethod in jQuery validator

$.validator.addMethod("validateEmail", function() { $.ajax({ type: "POST", url: "/user/check_email", data: { email: $( "#email" ).val() }, success: function(data) { console.log(dat ...

Vue has issued a warning stating that the type check for the "eventKey" prop has failed. The expected type was a String or Number, but an Array was provided instead. Additionally, it is advised to

The code I am currently using is producing the following errors in the console output: [Vue warn]: Avoid using non-primitive value as key, use string/number value instead. [Vue warn]: Invalid prop: type check failed for prop "eventKey". Expected String, ...

Conceal multiple divs at the same time based on their largest dimension

I am facing an issue with two divs, each containing two nested divs: https://i.sstatic.net/QFMiU.png <div class="hide"> <div> Variable size </div> <div> Text1 (also variable size) </div&g ...

Troubleshooting typescript error in styled-components related to Material-UI component

When using typescript and trying to style Material UI components with styled-components, encountering a type error with StyledComponent displaying Type '{ children: string; }' is missing the following properties import React, { PureComponent } f ...

Ways to boost performance in an Angular 6.0 application

https://i.stack.imgur.com/Rq9Y2.jpg We have recently developed a cutting-edge application using Angular 6, hosted on an Apache 2.4 server. To ensure our website is properly crawled by search engines, we set up a local "prerender" instance. Initially, we t ...

Issues with finding your way

Whenever I am in the History.js file and click on a product list item to navigate to another page for more details and contact the seller, the issue arises. When I click on an item in History.js, nothing happens on that page. However, when I switch to Home ...

Presenting two arrays simultaneously creates angular duplicates

Encountering an issue while trying to display two arrays containing channel information: List of channels List of subscriptions that users have opted for. channels = [ { "id": 1, "name": "arte", "service&q ...

Utilizing Sails.js: Invoking a YouTube service through a controller

I am facing an issue while trying to integrate Youtube Data API with Node.js in Sails.js. The problem lies with the "fs.readFile" function. Upon launching the service, it returns "undefined". Below is the code snippet for YoutubeService : module.exports ...

The module './product' could not be located, resulting in error TS2307

app/product-detail.component.ts(2,22): error TS2307: Cannot find module './product'. I have tried several solutions but none of them seem to work for me. I am working on a demo app in Angular 2 and encountering this specific error. Any guidance ...

How can I retrieve the OptionID value upon click?

How can I retrieve the value of OptionID when the Add button (.plus-link) is clicked? Each list item may contain a dropdown select menu or not. <ul> <li> <div class="menux"> <div class="text-block"> ...

Is it possible to execute TypeScript class methods in asynchronous mode without causing the main thread to be blocked?

Creating an app that retrieves attachments from specific messages in my Outlook mail and stores the data in MongoDB. The challenge lies in the time-consuming process of receiving these attachments. To address this, I aim to execute the task in a separate t ...

Navigating with Buttons using React Router

Header: I need help figuring out how to properly redirect to a new page when clicking on a Material UI button using the onClick method. Specifically, I am unsure of what to include in my handleClickSignIn function. Here is a snippet of code from my Header ...

Acquiring JSON data from Node.js within Angular

After searching everywhere, I finally managed to retrieve all the data from my database using node and saved it into a file. The data is simple JSON chat logs that can be accessed through my browser with ease. Here's a snippet of how it looks: [{ " ...

How to append a JSON object to an existing .json file

UPDATE: Despite successfully executing the PHP code, my JSON file remains unchanged. I must apologize in advance for covering old ground, but I have spent countless hours exploring different solutions with no success. Perhaps sharing my challenge could as ...