Sanyam Madaan
Sanyam Madaan

Reputation: 139

How to get data from array object in angular typescript?

I am calling a rest api which returns the data in json array of object format like this enter image description here

Now when I call this rest api from my typecsript code and print on console data received i get this

gameRecord: Fifa = new Fifa(); // this is defined globally in ts class

this.fifaService.fetchGameRecord(gameId).subscribe(
          data => {
            this.gameRecord = data;
            console.log(this.gameRecord);
          }
        );

enter image description here

Now I want to get the wonBy, kashScore attributes value from this object.

But I get undefined error on console, I don't know why

gameRecord: Fifa = new Fifa();


this.fifaService.fetchGameRecord(gameId).subscribe(
      data => {
        this.gameRecord = data;
        console.log(this.gameRecord.kashScore);
      }
    );

Here Code Definations,

export class Fifa {

    gameId: number;
    kashScore: number;
    samScore: number;
    wonBy: string;
    createUserId: number;
    lastModifiedUserId: number;
    creationDate: Date;
    lastModifiedDateTime: Date;
    sessionId: number;
}

And my service file code

fetchGameRecord(gameId: number): Observable<Fifa>{
    const fifaUrl = `${this.baseUrl}/getGameDetail/${gameId}`;
    return this.httpClient.get<Fifa>(fifaUrl);
  }

Upvotes: 1

Views: 7030

Answers (2)

Yug Damon
Yug Damon

Reputation: 501

gameRecord: Fifa = new Fifa();

this.fifaService.fetchGameRecord(gameId).subscribe(
      data => {
        this.gameRecord = data[0]; // <= data is an array
        console.log(this.gameRecord.kashScore);
      }
    );

Upvotes: 2

Shlok Nangia
Shlok Nangia

Reputation: 2377

here data is an array of type Fifa objects, not single object

so you can access it like this.gameRecord[0].kashScore Also you might need to update gameRecord: Fifa = new Fifa() this statement if you are expecting more records in the array as this.gamerecord will be array of objects else you can access the 0th element of array every time

Upvotes: 1

Related Questions