0

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. enter image description here

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!

Hex
  • 59
  • 6
  • 1
    It's the same problem. `subscribe` is called asynchronously and you are not waiting until it's finished. But I'm not deep enough into angular for guiding you how to wait on subscribe to finish (if thats even possible). But this has probably been asked multiple times here ... – derpirscher Jun 15 '22 at 09:06
  • 1
    You are mixing `Promise`s with `Observable`s here. You can not `await` an `Observable`. Try to stick to a solution using `Observable`s only. – Tobias S. Jun 15 '22 at 09:08
  • Okay, I'll try to do one or the other, but not both. – Hex Jun 15 '22 at 09:33

0 Answers0