为什么我的变量在 http 请求后没有改变?
Why don't my variables change after http request?
larnacaCount=0;
nicosiaCount=0;
private array :number[] = [];
constructor(private http: HttpClient, private popupService: PopupService) { }
makeCapitalMarkers(map: L.Map): any {
this.http.get(this.capitals).subscribe((res: any) => {
this.larnacaCount=res.larnaca; //should return 3
this.nicosiaCount=res.nicosia; //should return 1
console.log(res);
for (const c of res.features) {
const lon = c.geometry.coordinates[0];
const lat = c.geometry.coordinates[1];
const marker = L.marker([lat, lon]);
marker.bindPopup(this.popupService.makeCapitalPopup(c.properties));
marker.addTo(map);
}
});
this.array.push(this.larnacaCount);
this.array.push(this.nicosiaCount);
console.log(this.array)
return this.array; // this array is (0,0)
我尝试推送到数组中的 2 个变量在 http 请求中正确显示,但完成后它们返回到 0 和 0
Http 本身就是异步的。在您的情况下,执行顺序为:
Call this.http.get(但回调将在稍后调用,因为它是异步操作)
this.http.get(this.capitals)
执行同步代码(将元素推入数组并 returning this.array
的代码)
执行 this.http.get
的回调,您将在其中分配值
如果您需要数组值作为 makeCapitalMarkers
方法的 return 值,那么该方法应该是异步方法并且应该具有 return 类型的 Promise 或 Observable。
larnacaCount=0;
nicosiaCount=0;
private array :number[] = [];
constructor(private http: HttpClient, private popupService: PopupService) { }
makeCapitalMarkers(map: L.Map): any {
this.http.get(this.capitals).subscribe((res: any) => {
this.larnacaCount=res.larnaca; //should return 3
this.nicosiaCount=res.nicosia; //should return 1
console.log(res);
for (const c of res.features) {
const lon = c.geometry.coordinates[0];
const lat = c.geometry.coordinates[1];
const marker = L.marker([lat, lon]);
marker.bindPopup(this.popupService.makeCapitalPopup(c.properties));
marker.addTo(map);
}
});
this.array.push(this.larnacaCount);
this.array.push(this.nicosiaCount);
console.log(this.array)
return this.array; // this array is (0,0)
我尝试推送到数组中的 2 个变量在 http 请求中正确显示,但完成后它们返回到 0 和 0
Http 本身就是异步的。在您的情况下,执行顺序为:
Call this.http.get(但回调将在稍后调用,因为它是异步操作)
this.http.get(this.capitals)
执行同步代码(将元素推入数组并 returning
this.array
的代码)执行
this.http.get
的回调,您将在其中分配值
如果您需要数组值作为 makeCapitalMarkers
方法的 return 值,那么该方法应该是异步方法并且应该具有 return 类型的 Promise 或 Observable。