简体   繁体   English

可观察的返回单个数组

[英]Observable return single Array

Problem: 问题:

I want to return a single array at once, instead of multiple arrays currently being returned one-by-one. 我想一次返回一个数组,而不是当前一个一个返回的多个数组。

Code: 码:

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
}

How can I go about getting the array after all the pushing is done? 完成所有推送后,如何才能获得阵列?

There are couple of problems in this code: 此代码中有几个问题:

If properly rewritten it might look like this: 如果正确重写,它可能看起来像这样:

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

Observable subscribe implements 3 methods: onNext , onError , onCompleted . 可观察的订阅实现3种方法: onNextonErroronCompleted

.subscribe( 
data=>{ onNext},
err=>{ onError},
()=>{ onCompleted}
)

onCompleted will trigger last iteration of onNext . onCompleted将触发onNext最后一次迭代。 You can define next in onCompleted . 您可以在onCompleted定义下一个。

Refer to http://reactivex.io/documentation/operators/subscribe.html for more information 有关更多信息,请参考http://reactivex.io/documentation/operators/subscribe.html

My point is here first fetch the data from 'Api/driver/all'. 我的意思是,首先要从“ Api / driver / all”中获取数据。 In subscribe method you have 3 methods to implement. 在subscription方法中,您可以实现3种方法。 'OnNext','OnError'and'OnCompleted'. 'OnNext', 'OnError'and'OnCompleted'。 You can return observable in error and completed. 您可以返回observable错误并完成。

Please check the below code 请检查以下代码

 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
                      })
                    }
                  })

              }
            });
          })
          //looping ends 
        },
        err=>{
            return Observable.create(observer=>{
                observer.next(this.distances);
            })
        },
        ()=>{
            return Observable.create(observer=>{
                observer.next(this.distances);
            })
        })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM