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

The object literal's property 'children' is assumed to have a type of 'any[]' by default

Is there a way to assign the property myOtherKey with any value? I encountered a Typescript error that says.. A problem occurred while initializing an object. The property 'children' in the object literal implicitly has an array type of 'a ...

Unable to apply "@angular/fire" using ng add command because the package does not have schematic support

Just completed the upgrade to Angular CLI 12.0.0, alongside Node 14.17.0 and npm 7.13.0 Encountering an issue when attempting to integrate Angular Fire into my project: ng add @angular/fire The following message pops up: The package @angular/[email ...

In order to work with Mongoose and Typescript, it is necessary for me to

I am currently following the guidelines outlined in the Mongoose documentation to incorporate TypeScript support into my project: https://mongoosejs.com/docs/typescript.html. Within the documentation, there is an example provided as follows: import { Sche ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

Having trouble executing the typescript build task: Command 'C:Program' is not valid as an internal or external command

I'm currently working on converting typescript code to JavaScript and have been following the steps outlined in the documentation. To automate the compilation of .ts files, I set up a watch task triggered by pressing Ctrl+Shift+B. However, upon runni ...

ng2-select2 prevent selection of initial value

My Angular project has the following setup: Hello.component.html <select2 ngDefaultControl [data]="list" [options]="{ placeholder: placeholder }" > </select2> Hello.component.ts list = [ { id: 1, text: 'Item 1 one' }, { i ...

Is a special *ngFor required when implementing Angular2 with Nativescript?

My current project involves creating a mobile app that requires listing a few labels. Here is the code snippet: @Component({ selector: 'code-m', template: ` <StackLayout dock="top" orientation="vertical" style="height: ...

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

Firebase Angular encountering issues with AngularFirestoreModule

I have encountered a challenge with Firebase authentication in my Angular applications. Due to updated read and write rules that require auth!=null, I successfully implemented Firebase authentication in one of my apps using Angular 13. Now, I am trying to ...

Refresh an Angular page automatically

Having a small issue in my angular application. The problem arises on the first page where I display a table listing all employees along with a "Create New Employee" button that opens a form for adding a new employee. However, after submitting the form and ...

Calculate the variance in days between two dates and assign the result to a separate field

I am working with two date fields, one labeled Commencement Date and the other as Expiration Date. Objective: The goal is to calculate the difference in days between the selected commencement and expiration dates (expirationDate - commecementDate) and ...

The system encountered an error while trying to access the property 'enabled' of an undefined object

When working on a reactive form in my code, I need to ensure the values are properly set for the controls. ngDoCheck() { setControlValues(); } ngChanges(changes: SimpleChanges): void { setControlValues(); } private setControlValues() { try { ...

Please indicate the data type in Vue using Typescript

I'm currently struggling with Vue (3) + Typescript while attempting to specify a data property with a specific type. I have created a .d.ts file, but unfortunately, it hasn't helped. This is what I'm trying: import Modeler from 'bpmn-js ...

Exploring the possibilities of combining colspan and ngFor in an Angular material 6 table

Angular Material is being utilized for table rendering in my project. Code: <ng-container matColumnDef="type"> <th mat-header-cell *matHeaderCellDef> Workout type </th> <td mat-cell *matCellDef="let workout"> {{workout.type} ...

Guide on importing SVG files dynamically from a web service and displaying them directly inline

With an extensive collection of SVG files on hand, my goal is to render them inline. Utilizing create-react-app, which comes equipped with @svgr/webpack, I am able to seamlessly add SVG inline as shown below: import { ReactComponent as SvgImage } from &apo ...

Accessing information from a component using ComponentFactoryResolver in Angular 2

I have a grid component and I'm looking to enhance it by incorporating filters for each column. Specifically, I have various filter types for different columns such as simple text input, option filter, date range filter, and more. To achieve this func ...

How to prevent redundant object declarations when passing parameters in TypeScript?

Motivation for Using Object Parameters One of the motivations behind using objects as function parameters is to allow the caller to clearly define arguments with specified field names, which can make code reviews easier. Challenge When Using Implements an ...

Passing objects to Angular 4 routes while maintaining Query Params unchanged

I'm currently working with Angular 4 and I need to pass an object to the router without updating query parameters. user.component.ts this.router.navigate(["/profile",{ action: 'edit', user: {id: 1, name: 'test', email: &apo ...

Ensure that missing types are included in a union type following a boolean evaluation

When working with typescript, the following code will be typed correctly: let v: number | null | undefined; if(v === null || v === undefined) return; // v is now recognized as a `number` const v2 = v + 2; However, if we decide to streamline this process ...