Using a for loop with Angular 2 Observable.forkJoin

My current approach:

getTwoObjectById(url1: string, id1: string, url2: string, id2): any{
  return Observable.forkJoin(
    this.http.get(url1 + `/${id1}`, this.jsonWebToken()).map(res => 
      res.json()),
    this.http.get(url2 + `/${id2}`, this.jsonWebToken()).map(res => 
      res.json())
  );
}

I am looking for a way to generalize the function above to handle multiple IDs and URLs dynamically.

I am attempting to create a new function that accepts arrays of IDs and URLs as parameters. Using Observable.forkJoin, a loop will execute requests for each ID using the corresponding URL from the arrays.

getObjectsById(ids: Array<string>, urls: Array<string>): Observable<any>{
  return Observable.forkJoin(

  for(let i = 0; i++; i<ids.length) {

     this.http.get(urls[i] + `/${ids[i]}`, this.jsonWebToken()).map(res => res.json());

  }

 )
}  

I am facing challenges with implementing the loop functionality in the newly proposed function.

Answer №1

Consider utilizing the following code snippet

dataList = [5, 6, 7, 8];


fetchDataById() {
    let batchRequest = [];

    this.dataList.forEach((id) => {
      batchRequest.push(this.http.get(url+id).map((response) => response.json()));
    });

    return Observable.forkJoin(batchRequest);
  }

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

Encountered a bug in the findUnique function within the services of a Nest JS and Prisma project

I have a question about using Prisma with Nest. I keep encountering this error: src/modules/auth/auth.service.ts:28:63 - error TS2322: Type 'UserWhereUniqueInput' is not assignable to type 'string'. 28 const user = await this.prisma ...

Explore an example of using TypeScript to design and configure column search properties in a

Currently, I am utilizing the ant component available at https://ant.design/components/table/. Adding a search feature to my table has been quite challenging. The specific search option I am trying to incorporate can be viewed here: https://i.sstatic.net/l ...

Exploring the world of nested routes in Angular and how to efficiently

Hey there! I'm brand new to all of this and still trying to wrap my head around a few things, so any guidance you can offer would be awesome! :) Overview I've got a bunch of projects (/projects) Clicking on a project takes me to a detailed sum ...

Assistance with debugging Angular 2 alongside Express in Visual Studio Code

I have been attempting to configure a debugger in Visual Studio Code for my TypeScript project, but I find myself stuck and frustrated. Let me provide you with an overview of my project structure: ├───.vscode ├───dist │ ├───cli ...

Retrieve information from the API following a change in language with Ngx-Translate

I am working on a web app using Angular 12 that supports 3 languages. To manage the languages, I have utilized Ngx-Translate. Overall, everything is functioning correctly, but I have encountered a small issue. I am using the onLangChange event emitter to ...

I am having trouble combining my custom middleware with the default middlewares in my store configuration when using redux persist and rtk query

Here is the content of my store.ts file: import storage from 'redux-persist/lib/storage'; // defaults to localStorage for web import { FLUSH, PAUSE, PERSIST, persistReducer, persistStore, PURGE, REGISTER, REHYDRATE } from 're ...

Utilizing Angular 2's *ngFor to conditionally wrap elements can be compared to organizing a layout with three columns in a Bootstrap row, then starting a

Currently I am facing a challenge with using *ngFor and it has me puzzled. My goal is to incorporate UIkit, but the same concept would apply to Bootstrap as well. <div *ngFor="let device of devices" > <div class="uk-child-width-expand@s uk-te ...

Messages from the websocket, rxjs, and .net are currently not coming through to me

Currently, I am attempting to implement a straightforward WebSocket solution where an integer is sent to the socket from a dotnet application and then retrieved in my rxjs. The sending process is simple and error-free. Assuming that values are being succe ...

Having difficulty sending a message from an AngularJS application to an Angular 10 application through an iframe

I have two applications running locally - one is an AngularJS application and the other is an Angular 10 application. I am trying to access a page from the Angular 10 application using an iframe and send a message to it from the AngularJS application. How ...

Error in Angular: The type 'Response' is not generic

Currently, I am attempting to extract a nested array from an HTTP response with Angular 14 getItems(): Observable<Item[]> { return this._httpClient.get<Item[]>(this.apiUrl + 'items').pipe( tap((items) => { t ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Type-safe Immutable.js Records with TypeScript

I'm struggling to find a suitable solution for my query. I am aiming to define data types using an interface in TypeScript, but my data consists of Immutable.js records making it more complex. Please refer to the example provided below. interface tre ...

An anomaly with the checkbox editing feature in the PrimeNG table

Within my Angular 5 application, I am utilizing the PrimeNG "turbo" table component and encountering an issue while trying to edit a checkbox. If you want to learn more about PrimeNg tables, visit primeNg - table https://i.sstatic.net/ryZ2A.gif As depict ...

Tips for maintaining knowledge after redirecting to a new page

Building an app using Ionic 4 where I need to display vouchers from a database as images. Each image should act as a link to a details page showing more information about that specific voucher. However, I am struggling to figure out how to keep track of th ...

I am experiencing sluggish performance with my React App when running on LocalHost, yet it runs smoothly on Live Server. The UI rendering is noticeably slow. What might be causing this issue?

Currently, I am tackling a React-TS App. It appears to load smoothly on the live server, but in dev mode on localhost, it experiences significant sluggishness. Despite conducting thorough research, I have yet to find a solution. Here is a snippet from my p ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Adding a second interface to a Prop in Typescript React: a step-by-step guide

import { ReactNode, DetailedHTMLProps, FormHTMLAttributes } from "react"; import { FieldValues, SubmitHandler, useForm, UseFormReturn, } from "react-hook-form"; // I am looking to incorporate the DetailedHTMLProps<FormHTMLAt ...

What is the method for extracting search parameters as an object from a URL that includes a hash symbol?

Currently, I am dealing with a URL structured in the following format: https://my-app.com/my-route/someOtherRoute#register?param1="122"&param2="333" While I am familiar with fetching query strings from a standard URL, I am struggli ...

I am currently facing an issue related to the length property. It is showing an ERROR TypeError: Cannot read property 'length' of undefined

Is it recommended to set the length to be inherited from Angular right? If so, why am I getting this error: "MyPostsComponent.html: 7 ERROR TypeError: Cannot read the 'length' of undefined property" when fileList.length is greater than 0? onFile ...

When accessing APIs, create an array of observables for each user call and then trigger a function once all are successfully resolved

As I aim to generate a list of observables while a user engages with the webpage, I am faced with the challenge of individually subscribing to each observable, but desiring another function to execute after individual or multiple simultaneous API calls are ...