What is the best way to send an array of locationIds to the getLocationData service?

Seeking Assistance on Sending an Array of Location IDs to a Service

I currently have an array consisting of location IDs.

locationArr=[40871, 60009, 38149, 40868, 43240, 15299, 53897, 40976, 38151, 23183, 38152, 78579, 23180, 40977, 23176, 39565, 40884, 15298, 38147, 40966, 39669] 

I am in need of passing this locationArr array to

The purpose is to send the array of location IDs present in locationArr to a service in order to retrieve the latitude and longitude coordinates for each location ID within that array.

The current situation is that the service can only fetch the data for one location ID at a time. Therefore, my query is about how to handle an array of location IDs efficiently.

getLocationData(id: number) {  
console.log("server "+id)  
return this.http.get('http://192.168.7.45:9200/location/_doc/'+id);  
}  

Hence, I would greatly appreciate guidance on how to accomplish this using a loop through the array of locations.

Calling the service
this.partDetailsService.getLocationData(this.LocationId).subscribe(res => {          
         this.dataLocation = res['_source']['GPS1'];     
         var loc = this.dataLocation.split(',');      
         this.lat = loc[0].trim();    
         this.lng = loc[1].trim(); 

Answer №1

Initially, make sure your backend is capable of accepting multiple locationIds instead of just one. This will allow you to send the necessary data based on these ids.

If your backend can handle multiple Ids as comma-separated values in a GET request, your Angular code should look like this:

getLocationData(ids: Array<number>) {  
   console.log("server "+ids)  
   return this.http.get('http://192.168.7.45:9200/location/_doc/'+ids.join(','));  
} 

If your backend can accept multiple Ids in an array within a POST body, your Angular code should be structured as follows:

getLocationData(ids: Array<number>) {  
   console.log("server "+ids)  
   return this.http.post('http://192.168.7.45:9200/location/_doc/', { ids: ids });  
}  

If your backend does not support multiple Ids, you'll need to iterate through each id and call the backend separately for each one:

getLocationData(ids: Array<number>) {  
    let observableBatch = [];

    this.ids.forEach((id) => {

        observableBatch.push(
              this.http.get('http://192.168.7.45:9200/location/_doc/'+id)
                       .map((res) => res.json()));
    });

    return Observable.forkJoin(observableBatch);
}


this.partDetailsService.getLocationData(this.LocationIds).subscribe(res : Array<any> => {  
         Since it's an array, you need to iterate through 'res'        
         res.forEach((item, index) => {
            const dataLocation = res[index]['_source']['GPS1'];     
            const loc = this.dataLocation.split(',');      
            this.lat[index] = loc[0].trim();    
            this.lng[index] = loc[1].trim();
         });
}

In summary, the API signature of your backend determines how it should be called.

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

Make sure to utilize flatMap to call the second API every time

I am utilizing two APIs, API1 and API2. The output from API1 is used as an input for API2. In case the call to API1 fails, I still want API2 to be invoked with a blank value. this.Api1().pipe(flatMap(result => { return this.Api2(result); })).subscrib ...

A step-by-step guide on assigning values to an Angular Material Auto Complete component in Angular 7

Hey there! I'm currently using the Angular Material Auto complete component in my Angular 7 app and I'm trying to find a way to bind a value from an API response to it. Can someone help me out with a solution for this? HTML: <mat-form-field> ...

Utilizing TypeScript to define the parameter of a method within a generic interface by extracting a value from the generic type

In search of defining a versatile interface that can manage any Data type, I came up with an idea. This interface includes a dataKey property which simply holds a value of keyof Data. Additionally, it features a handler function where the parameter type sh ...

p-menu fails to appear

I'm currently experimenting with Primeng and Angular 2 to put together a basic menu. Take a look at my code snippet: import {Component, OnInit} from '@angular/core'; import {Menu, MenuItem} from 'primeng/primeng'; @Component({ ...

I am looking to update the color based on the prop value in React

Currently using react along with typescript. My objective is to adjust the color based on the value passed through props. The props will contain either "primary," "secondary," or "brand" as a string type. When the value "primary" is provided, I aim ...

Angular Fails to Identify Chart.js Plugin as an Options Attribute

Encountering issues with using the 'dragData' plugin in Chart.js 2.9.3 within an Angular environment: https://github.com/chrispahm/chartjs-plugin-dragdata After importing the plugin: chartjs-plugin-dragdata, I added dragdata to the options as sh ...

Calculate the time difference between the stroke of midnight on a specific date and the present moment using JavaScript, node.js, and

Looking for a way to determine if the current moment is less than 3 minutes after midnight of the next date using a JavaScript Date object (e.g. 09.08.2020 15.45). This condition should evaluate to true for times ranging from 09.09.2020 00:00 up until 09.0 ...

Angular and KeyCloack - Automatically redirect to specific route if user's role does not have access permissions

I am currently working on implementing a mechanism to redirect unauthorized roles when attempting to access restricted routes using the keycloack-angular library: npm install keycloak-angular keycloak-js Custom Guard Implementation export class AuthGuar ...

Uncovering the Full Scope of a LinkedIn Profile with Typescript

Hello, I am currently in the process of developing an Ionic2 framework app that includes social login functionality. Up to this point, I have successfully integrated Google Plus and Facebook buttons. Now, I would like to add LinkedIn login as well. The c ...

Encountering an issue with Angular 2.0.1 Router where it throws an EmptyError due to

I am struggling to set up Angular 2 routing properly. I am currently using Angular 2 with Webpack. While looking at the Angular 2 webpack starter, I noticed they had webpack handling their html and links generation, but I was hoping to avoid webpacking my ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

Observable - initiating conditional emission

How can I make sure that values are emitted conditionally from an observable? Specifically, in my scenario, subscribers of the .asObservable() function should only receive a value after the CurrentUser has been initialized. export class CurrentUser { ...

Unraveling the Mechanics of ngFor in Angular

I am looking to optimize my code. In the section-portrait.component.html file, I have this ngFor loop: <app-portrait *ngFor="let model of models" [firstName]="model.firstName" [lastName]="model.lastName" ></app-portrait> This ...

Encountering an issue with extending the MUI color palette, receiving a "reading 'dark'" error due to properties of undefined

Encountering an issue when trying to expand the MUI color palette—getting this error instead: Error: Cannot read properties of undefined (reading 'dark') Take a look at my theme.ts file below: const theme = createTheme({ palette: { pri ...

Having trouble with CSS Locator identifying an element in your Protractor Test?

In the Protractor test snippet below, I am attempting to calculate the quantity of div elements using the CSS locator: let list = element.all(by.css('div[class="ag-header-cell ag-header-cell-sortable"]')); expect(list.count()).toBe(11); ...

Every time I make updates, I have to reload the page to see the changes take effect

Currently, I am in the process of developing a web application that utilizes Firebase Firestore as the backend and NoSQL database, with Angular serving as the frontend. With frequent updates and changes being made to the website, it becomes cumbersome to c ...

Utilize Angular to associate a value with a directive parameter

I'm currently working on a directive that will alter the text of a button based on a specific condition. For instance, during the saving process of a form, I want the submit button to display "Saving..." until the processing is complete, and then reve ...

Why hasn't the variable been defined?

Why am I receiving an error message saying "test is not defined" in this code? Even though I have properly defined the variable in another service file, it seems to be causing issues here. Any insights on what could be going wrong? import { Injectable } f ...

Is it possible for TypeScript to preserve the return type while consolidating multiple classes or objects of functions in a reducer method?

Describing my issue with the title was challenging, but here it is: I have several objects that follow this structure: type TUtilityFunction = {[key: string]: <T>(a: T, b: any) => T} For example: class UtilityA{ DoSomeWork = function (arg1: So ...