I'm making a memory card game as hobby project. A few days ago I ran into a similar problem, which was solved by: How to return the response from an asynchronous call
But I now rewritten my code to use Angular's GET function, instead of outdated fetch, but now when I try to print my array after getting them the console.log shows an empty list, and I'm not sure why this happens, the cards I get from the server show up just fine, I just cannot shuffle them because I cannot do array operations on them.
Here is what the browser shows.
Here is the relavant part of my code:
In the service:
private extractData(res: Response) {
let body = res;
return body || {};
}
public async getJSON(url: string): Promise<Observable<any>> {
// Call the http GET
return this.http.get<Response>(url).pipe(map(this.extractData),catchError(this.handleError)
);
}
getCards(): Observable<Card[]> {
const cards = of(CARDS);
console.log(cards);
return cards;
}
Here is what's in the gameboard:
async getCards() {
this.cardService.getCards().subscribe(cards => this.cards = cards as Card[] );
//this.cardService.getSuffledCards().subscribe(cards => this.cards = cards);
}
shuffleArray(anArray: any[]): any[] {
console.log(anArray.length);
return anArray.map(a => [Math.random(), a])
.sort((a, b) => a[0] - b[0])
.map(a => a[1]);
}
async fetchCards() {
var counter : number = 0;
(await this.cardService.getJSON(this.url)).subscribe(
async data => {
try {
while(data['posts'][counter]['file']['url']) {
var newCard: Card = {id:0,pairId:counter,state:'default',shape:"s",picture:data['posts'][counter]['file']['url']}
this.cardService.create(newCard);
this.cardService.create(newCard);
counter++;
}
} catch {
}
},
err => {
console.log(err);
}
)
}
async ngOnInit(): Promise<void> {
await this.fetchCards();
await this.getCards();
console.log(this.cards); //These are what's get printed in the browser
this.shuffleArray(this.cards);
console.log(this.cards);
}
What could be the problem? Am I missing an async/await from somewhere, maybe a subscribe?
I wish everyone a ncie day!