如何从角度打字稿中从数组对象获取数据?

时间:2020-04-20 11:28:03

标签: javascript angular typescript observable httpclient

我正在调用rest api,它以这种对象格式返回json数组中的数据 enter image description here

现在,当我从typecsript代码中调用此rest api并在收到的控制台数据上打印时,我得到了

gameRecord: Fifa = new Fifa(); //这是在ts类中全局定义的

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

enter image description here

现在,我想从该对象获取wonBy,kashScore属性值。

但是我在控制台上收到未定义的错误,我不知道为什么

gameRecord: Fifa = new Fifa();


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

这里的代码定义

export class Fifa {

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

我的服务文件代码

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

2 个答案:

答案 0 :(得分:1)

此处数据是Fifa类型对象的数组,而不是单个对象

因此您可以像this.gameRecord[0].kashScore一样访问它 另外,如果您希望数组中有更多记录,则可能需要更新gameRecord: Fifa = new Fifa()该语句,因为this.gamerecord将是对象数组,否则您每次都可以访问数组的第0个元素

答案 1 :(得分:1)

gameRecord:Fifa =新的Fifa();

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