angulartypescriptangular-materialangular7angular-resource

How to pass array of locationId to service getLocationData?


How to pass array of locationId to service ?

I have array of locations Id

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

Actually I need to pass locationArr to http://192.168.7.45:9200/location/_doc/+locationArr

I need to pass array of locationId exist on locationArr to service to get GPS1 latitude and longitude for every locationId on array locationArr.

service get location by locationId for only one locationId but for array of location this is my question

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

so please How to achieve it by loop within array of location

calling 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(); 

Solution

  • First of all your back-end needs to be changed to accept multiple locationId, seems it's only accepting one, then based on that you can send your data.

    If your back-end will support multiple Ids as comma separated values in GET then your angular code will be like below

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

    If your back-end will supports multiple Ids as an array of POST body then your angular code will be like below

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

    If your back-end doesn't support multiple Ids, then you need to loop through ids and call the backend for each

    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 needs to loop 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();
             });
    }
    
    

    All in all, back-end api signature drives how to call it