2017-09-12 7 views
1

私はmergeMapを使用して、ポイントに基づいてアドレスを見つける一組のクエリを生成しています。私は各応答をオブジェクトの配列にマップします。mergeMapがあまりにも早く完了しました

//ptosDistintos = ['-34.5466 58.4363', '-34.5523 58.4486', ...] 
this.suscCalcularDirecciones = Observable.from(ptosDistintos) 

    .mergeMap(pos => { 

     //I convert every position to a latLng object (Leaflet) 
     const [lat, lng] = pos.split(' '); 
     const latlng = L.latLng(+lat, +lng); 

     //I make requests to Google to figure out addresses 
     return this.http.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latlng.lat},${latlng.lng}`) 
      .filter(x => x.length) 
      //I return the address to the mergeMap. 
      .map(direccion => 
       [pos, direccion.length ? direccion[0].formatted_address : '(no encontrada)']; 
      ); 
    }) 
    .finally(() => { 

     //I'm deleting the suscription once it is complete because in template I check for completion by checking emptyness of the subscription. 
     delete this.suscCalcularDirecciones; 
    }) 
    .subscribe(posDir => { 
     const [pos, dir] = posDir; 
     for (let i of agrup[pos].indexes) { 
      this.historico[i].direccion = dir; 
     } 
     this.historico = this.historico.slice(); 
    }); 

ただし、me​​rgeMapによって生成される観測値は、あまりに早く完了しています。 "finally"命令は、 "nexts"のいくつか(最初ではないにしても)の後に実行されます。 Googleへのすべてのクエリが完了したら、私はそれを呼び出すために何ができますか?

+0

デモを作成できますか?コードは 'delete this.suscCalcularDirecciones'を除いて私にはうまく見えます。これを行う必要はありません。 – martin

+0

私はサブスクリプションの空きをチェックしてhtmlの補完をチェックしたいからです。私は、もし私がその行を削除しても、これは何の役にも立ちません。私の質問は、なぜこれが起こっているのかを指しています。 私はデモを試みましたが、stackoverflowスニペットツールでRxjsをインポートする際に問題がありました。 : – Umagon

+0

このテンプレートを使用することができますhttp://jsbin.com/bumeroq/2/edit?html,js,output – martin

答えて

2

最後に、Google APIに問題がありました。

.filter(x => x.length) 

この行は、マージが失敗の多くを完了したので、Googleからの0結果が得られた回答を削除しました。これは、Googleが1秒間に多くのリクエストを行うことを許可していないためです(私はそれらをすべて同時に作成し、数百になることもあります)。

enter image description here

それは時間をかけて要求を行うので、私は、観察にタイマーを追加しました。

Observable.timer(0, 100) 
    .map(i=>ptosDistintos[i]) 
    .take(ptosDistintos.length) 
    .mergeMap(... 

希望すると、誰かに役立ちます。 google apisタグを追加します。

関連する問題