gpt4 book ai didi

angular - 以 Angular 形式保留 http 调用的顺序

转载 作者:行者123 更新时间:2023-12-02 16:32:21 25 4
gpt4 key购买 nike

我正在尝试使用我在 SO 上找到的几种方法来解决我面临的顺序问题。没有成功。

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

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

然后我有一个方法,其中发生 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;
});

}

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

最佳答案

由于 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);
});

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

从 'rxjs/observable/forkJoin' 导入 { 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));
})
}

关于angular - 以 Angular 形式保留 http 调用的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49377607/

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