以角度形式保留 http 调用的顺序

Gab*_*iel 2 rxjs angular angular-httpclient

我正在尝试使用我在此处找到的几种方法来解决我面临的订单问题,没有成功。

我有一个方法,可以为传单层数组加载一些数据:

private loadSelectedTileLayersCapabilities(): void {

        let tempTileLayer;

        this.selectedTileLayerIds.forEach(
            (selectedTileLayer: string) => {
                tempTileLayer = this.getTileLayerById(selectedTileLayer);

                this.capabilitiesService.getTileLayerDimensions(tempTileLayer.url, tempTileLayer.name, tempTileLayer.id)
                .subscribe(
                    dimensions => this.displayNewTileLayer(dimensions)
                );
            }
        );
    }
Run Code Online (Sandbox Code Playgroud)

然后我有一个方法,调用http发生在其中:

public getTileLayerDimensions(urlToFormat: string, tileLayerName: string, tileLayerId: string): Observable<Dimensions> {

        const capabilitiesUrl = `serviceUrl`;

        return this.httpClient.get(capabilitiesUrl, {responseType: "text"})
            .map(res => {

                // Doing stuff with data

                return dataForLayer;
            });

    }
Run Code Online (Sandbox Code Playgroud)

问题是,该displayNewTileLayer(dimensions)方法是按随机顺序调用的。有没有办法保留数组中项目的存储顺序 selectedTileLayerIds

Joh*_*ohn 5

由于 http 调用是异步的,因此响应可能不会按照请求的顺序到达。您可以做的是创建请求列表,创建 forkJoin等待所有响应解析。然后您可以displayNewTileLayer(dimensions)为所有响应调用 - 方法。

这是一个例子

    const httpCalls = []; // store the requests here
    for (let i = 0; i < 3; i++) {
      httpCalls.push(this.http.get('someUrl').map(response => response));
    }
    forkJoin(httpCalls).subscribe(res => {
      // all responses completed. returns an array of data (one for each response).
      console.log('res', res);
    });
Run Code Online (Sandbox Code Playgroud)

在您的情况下,此代码可能有效:(代码未经测试,您可能必须在代码中导入 forkJoin 运算符)

import { forkJoin } from 'rxjs/observable/forkJoin';

private loadSelectedTileLayersCapabilities(): void {

    let tempTileLayer;
    let requests = []:

    this.selectedTileLayerIds.forEach(
        (selectedTileLayer: string) => {
            tempTileLayer = this.getTileLayerById(selectedTileLayer);
            const request = this.capabilitiesService.getTileLayerDimensions(tempTileLayer.url, tempTileLayer.name, tempTileLayer.id)
            requests.push(request);

        }
    );
    forkJoin(requests).subscribe(res => {
      res.forEach(dimension => this.displayNewTileLayer(dimension));
    })
}
Run Code Online (Sandbox Code Playgroud)