如何将locationId数组传递给服务?
我有一组位置ID
locationArr=[40871, 60009, 38149, 40868, 43240, 15299, 53897, 40976, 38151, 23183, 38152, 78579, 23180, 40977, 23176, 39565, 40884, 15298, 38147, 40966, 39669]
实际上我需要将locationArr传递给http://192.168.7.45:9200/location/_doc/+locationArr
我需要传递locationArr上存在的locationId数组以进行服务,以获取数组locationArr上每个locationId的GPS1纬度和经度。
服务仅通过一个locationId通过locationId获取位置,但是对于位置数组,这是我的问题
getLocationData(id: number) {
console.log("server "+id)
return this.http.get('http://192.168.7.45:9200/location/_doc/'+id);
}
所以请如何在位置数组中循环实现
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();
答案 0 :(得分:0)
首先,您需要更改后端以接受多个locationId,似乎它仅接受一个,然后基于此您可以发送数据。
如果您的后端将在GET中支持多个Id作为逗号分隔的值,那么您的角度代码将如下所示
getLocationData(ids: Array<number>) {
console.log("server "+ids)
return this.http.get('http://192.168.7.45:9200/location/_doc/'+ids.join(','));
}
如果您的后端将多个Id作为POST正文数组支持,那么您的角度代码将如下所示
getLocationData(ids: Array<number>) {
console.log("server "+ids)
return this.http.post('http://192.168.7.45:9200/location/_doc/', { ids: ids });
}
如果您的后端不支持多个ID,那么您需要遍历ID并为每个ID调用后端
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();
});
}
总而言之,后端api签名驱动了如何调用它