Managing numerous HTTP requests and providing the outcome through Angular and Rxjs

Currently, I am facing a challenge with sending GET requests for a large number of URLs (50 of them) to the Spotify server and then returning their results in a single Observable/array/object.

This is the code snippet I have come up with:


curatedTopArtistTracks(artistIds) {
    let responseStore = [];
    for (let [index, artistId] of artistIds.entries()) {

      let baseURL = `https://api.spotify.com/v1/artists/${artistId}/top-tracks?country=US`;

      let response = this.http.get<any>(baseURL, { headers: this.customHeaders });

      response.subscribe(
        res => {
          responseStore.push(res.tracks);
        },
        error => {
          console.log('ERROR IN GETTING RESPONSE : INDEX : ', index);
        }
      );
    }
return responseStore;
}

The URL format is:

https://api.spotify.com/v1/artists/${artistId}/top-tracks?country=US
where ${artistId} varies dynamically for each of the 50 IDs.

MY OBSERVATIONS

While this function successfully sends the appropriate requests and receives a 200 OK response, the main issue is that the for loop does not wait for the HTTP requests to be resolved and returns an undefined responseStore.

I looked into concepts like ForkJoin and mergemap in Rxjs and tried to modify the code as shown below:

Example:


  curatedTopArtistTracks(artistIds): Observable<any> {
    let responseStore = [];
    for (let [index, artistId] of artistIds.entries()) {
      let baseURL = `https://api.spotify.com/v1/artists/${artistId}/top-tracks?country=US`;
      const requestURL = this.http.get(baseURL);
      responseStore.push(requestURL);
    }
    return forkJoin(responseStore);
  }

However, the above code does not initiate fetching responses because it seems that pushing the URLs into an array causes issues with how forkjoin processes them.

If you have any insights on how I can achieve the desired functionality, your help would be greatly appreciated!

UPDATE

As @martin pointed out in the comment below, I was not subscribing to the service. It functions correctly when I do subscribe, as shown below:


let response = this.service.curatedTopArtistTracks(artistArray).subscribe(
      res => {
        console.log('RESPONSE : ', res);
      },
      error => {
        console.log('error : ', error);
      }
    )

Answer №1

Give this a shot:

Try implementing it in the following way:

return request1().pipe(
  mergeMap(response1 => request2(response1.id).pipe(
    map(response2 => {
      return {
        data1: response1,
        data2: response2
      }
    })
  ))
)

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

Uploading raw data to Firebase bucket

I am currently developing a nodejs/typescript application that leverages Firebase Functions, and I am facing a challenge with uploading a JSON object to a bucket. The issue arises from the fact that the JSON data is stored in memory and not as an actual fi ...

Error encountered when importing a function in Typescript causes a compiler issue

When working with Typescript, I am utilizing the import function following the instructions provided at: https://github.com/Microsoft/TypeScript/issues/12933 My implementation looks like this: import("../myScriptToBeImported").then((module) => { ...

What is the best way to send a message to only one specific client using socket.io instead of broadcasting to everyone?

After thoroughly researching the documentation, I am still unable to find a solution. My goal is to send data to a specific client or user instead of broadcasting it to everyone. I have come across other inquiries regarding this issue, but most either rem ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

CAUTION: The presence of numerous imports of Three.js

I encountered a warning when attempting to utilize both @react-three/fiber and @react-three/drei in my project. https://i.sstatic.net/SkM2K.png Steps to replicate npx create-react-app reproduced-warning cd reproduced-warning npm install three @react-thre ...

Tips for keeping your Angular CDK up to date and improving its performance

Having just started with Angular, I'm stuck trying to figure out why the update is throwing errors. Purpose: Update the cdk and material versions, then install file-saver. Command: npm update @angular/cdk How can I update my angular cdk? Here&apos ...

Strings are concatenated in object literals by creating string attributes

When working with Javascript Object literals, I am facing an issue where string attributes cannot be concatenated properly. var cart = { baseURL : "http://www.domain.com/", addURL : this.baseURL + "cart/add", deleteURL : this.baseURL + "cart/delete" ...

The arrival of chat featuring Ajax, long-polling, and support for multiple users has finally

Imagine a site with three modules: "links", "home", and "chat". The "links" and "home" modules are static pages that do not require long polling. However, in the "chat" module, new messages may arrive at any time from other users, requiring an immediate up ...

What are the recommended guidelines for using TypeScript effectively?

When facing difficulties, I have an array with functions, such as: this._array = [handler, func, type] How should I declare this private property? 1. Array<any> 2. any[] 3. T[] 4. Array<T> What is the difference in these declarations? ...

Managing optgroup in select dropdown using Angular 4

Is there a way to retrieve the optgroup label value within an onchange function on a select box in Angular 4? In my form, I have a select box with multiple dates as option groups and time slots in 24-hour format for booking (e.g. 1000 for 10AM, 1200 for 1 ...

Unable to use model.find() in post findOneAndUpdate hook for Mongoose

Introduction In Mongoose, I am facing an issue with a post findOneAndUpdate hook where I need to perform a database query. Specifically, when trying to execute a .find() operation on another model, I encounter the following error: Error Description Typ ...

Is there a way to redirect the user directly to the upload page without displaying the response?

Recently, I came across this code snippet that adds a progress bar to an upload form. Currently, the code displays the response from the upload page below the form. However, my goal is to redirect the user to the upload page so they can view the response t ...

What is the best way to incorporate ControlContainer in an Angular component's unit test?

Is there a way to include ControlContainer in an Angular unit test? The error message I am encountering reads: NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]: StaticInjectorError(Platform: core) ...

We will explore the process of accessing a CSS file within an Angular

I'm having trouble reading a CSS file from my UI project directory in AngularJS. When I make a GET call, I only get the index.html file as output instead of the CSS file. Can anyone provide some guidance on how to properly access the CSS file? Any su ...

Trouble with saving $http get response data to a scope variable

Here is the code snippet that is facing an issue in assigning return values to the scope variable. app.factory("appService",function($http){ var promise; var lists = { async: function() { var promise = $http.get("http://localhost:81/hrms/pub ...

Error message: "Lazy-loaded modules encounter a TypeError stating that '' is not a function when accessed through NGINX."

Hey, I've got some distribution files for you to check out: AOT-enabled dist with Lazy Modules No AOT Lazy Modules dist AOT without Lazy Modules dist Here's what's been going on: When served locally with webpack-dev-server or live-serve ...

The object function router(req, res, next) is encountering an error as it does not contain the required method for handling the request

I am trying to add a new row to my MySQL database, but I encountered an error message. Here is the scenario: I have set up Passport and hjs in my project. I am passing form data from app.js to a JavaScript file where I aim to insert the data. Object funct ...

Unpredictable preset inline styles for HTML input elements

While developing a full-stack MERN application, I encountered an unusual issue when inspecting my React UI in Chrome DevTools. If any of these dependencies are playing a role, below are the ones installed that might be contributing to this problem: Tail ...

What causes Node.js to crash with the Headers already sent Error while managing errors in Express?

My current project involves using Express to set up an API endpoint for user registration. However, I've encountered a problem where sending a request that triggers an error to this API endpoint causes my node.js server to crash. The specific message ...

Guide on deploying a Node.js and Angular application on Google Cloud Platform

I currently have a setup where both my nodejs backend and angular frontend app are located in the same directory. The angular app generates build files in a static folder, and the nodejs backend serves the HTML file using the following code snippet: //Exp ...