Within my Angular application, I am facing an issue with the following code snippet located inside a method:
let cardArray: string[] = [];
this.cardService.getCards().subscribe((cards) => {
console.log("1", cards);
for (const card of cards.cards) {
cardArray.push(card.id);
}
console.log("2", cardArray);
});
console.log("3", cardArray);
The challenge here is that the number 3 gets logged before numbers 1 and 2. This results in the array being empty outside the observable but filled inside it. How can I ensure the data is available outside the observable? It is required towards the end of my function.
Thank you!
UPDATE: Additional code has been included
let cardArray: string[] = [];
this.cardService.getCards().subscribe((cards) => {
cardArray = cards.cards;
});
return this.http.post<Object>(
url,
{
cards: cardArray // <-- at this point, the array is empty
},
{
headers: headers
}
);