mergeMap完成得太早了

时间:2017-09-12 15:26:33

标签: google-maps-api-3 rxjs

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

但是,mergeMap生成的observable太早完成了。 "终于"在" nexts"中的一些(如果不是第一个)之后执行指令。在对Google的所有查询完成后,我该怎么做才能调用它?

1 个答案:

答案 0 :(得分:2)

最后,Google API存在问题。

.filter(x => x.length)

这一行删除了谷歌有0结果的回复,因此合并完成时出现了很多失败。这是因为Google不允许每秒发出如此多的请求(我同时制作了所有请求,有时候它们就是数百个)。

enter image description here

我在observable中添加了一个计时器,以便随着时间的推移发出请求。

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

希望这有助于某人。我将添加google apis标记。

相关问题