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
uj5u.com熱心網友回復:
Http 本身是異步的。在您的情況下,執行順序將是:
呼叫 this.http.get (但回呼將在稍后呼叫,因為它是異步操作)
this.http.get(this.capitals)執行同步代碼(將元素推入陣列并回傳的代碼
this.array)執行回呼
this.http.get,您在其中分配值
如果您需要陣列值作為makeCapitalMarkers方法的回傳值,則該方法應該是異步的,并且應該具有 Promise 或 Observable 的回傳型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/431283.html
上一篇:在電子應用程式中,我成功地從Angular組件發出HTTPGET請求。我怎樣才能從電子方面做同樣的事情?
下一篇:在一個組件中創建多個表單
