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)
My 2 variables that I try to push in the array appear correctly inside the http request but when that finishes they go back to 0 and 0
CodePudding user response:
Http is async per se. In your case order of execution will be:
Call this.http.get (but callback will be called later since its an async operation)
this.http.get(this.capitals)
Execute sync code (the one where you are pushing elements into array and returning
this.array
)Execute callback of
this.http.get
, where you are assigning values
If you need array value as a return value of your makeCapitalMarkers
method, then the method should be async one and should have return type of Promise or Observable.