gpt4 book ai didi

javascript - Observable 返回单个数组

转载 作者:行者123 更新时间:2023-12-03 02:52:14 25 4
gpt4 key购买 nike

问题:

我想一次返回一个数组,而不是当前逐一返回多个数组。

代码:

fetchAllRiders() {
var distanceObs = Observable.create(observer => {
this.http.get(this.API + '/driver/all').map(res => res.json())
.subscribe(data => data.map(rider => {
this.geocoder.geocode({
location: {
lat: rider.driver_lat,
lng: rider.driver_lng
}
}, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.distanceMatrixService.getDistanceMatrix({
origins: [this.from],
destinations: [results[0].formatted_address],
travelMode: google.maps.TravelMode.DRIVING
},
(response, status) => {
if (status == google.maps.DistanceMatrixStatus.OK) {
this.distances.push({
distance: response.rows[0].elements[0].distance.value,
rider_id: rider._id
})
}
})
observer.next(this.distances);
}
})
})
//looping ends
)
})
return distanceObs
}

所有推送完成后,如何获取数组?

最佳答案

这段代码有几个问题:

如果正确重写,它可能看起来像这样:

function fetchAllRiders() {
// it's better to rewrite this services so they will return Observable insated of using callback
const geocode = Observable.bindCallback(this.geocoder.geocode);
const getDistanceMatrix = Observable.bindCallback(this.distanceMatrixService.getDistanceMatrix);

return this.http
.get(this.API + '/driver/all')
.switchMap(res => res.json())
.mergeMap(rider =>
geocode({
location: {
lat: rider.driver_lat,
lng: rider.driver_lng,
},
})
.filter(([results, status]) => status === google.maps.GeocoderStatus.OK)
.switchMap(([results]) =>
getDistanceMatrix({
origins: [this.from],
destinations: [results[0].formatted_address],
travelMode: google.maps.TravelMode.DRIVING,
}),
)
.filter(([results, status]) => status === google.maps.DistanceMatrixStatus.OK)
.map(([response]) => ({
distance: response.rows[0].elements[0].distance.value,
rider_id: rider._id,
})),
)
.toArray();
}

关于javascript - Observable 返回单个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47802964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com