首页 > 解决方案 > 如何使用休息 API 使请求以角度工作

问题描述

我正在开发自己的项目,它是一个游戏库,我有一个单独的文件,其中包含我的硬编码数据,其中每个项目都有一个 ID 和一个名称。我遇到的问题是我的 component.ts 文件看不到 id 的值,即使我的 get 请求工作得很好并且在表中显示了 id 和名称。我正在关注一个教程,但对其进行了调整,因此它适用于我的,但是当我无法就我的具体问题寻求帮助时,这会导致问题。

我曾尝试更改变量名,以防我以这种方式搞砸了一些事情,但那并没有这样做,所以我不知道还能做什么老实说。

<table>
  <tr>
    <th></th>
    <th>Id</th>
    <th>Name</th>
  </tr>
  <tr *ngFor="let game of games">
    <button (click)="updateGame($game)" class="btn btn-default btn-sm">Update</button>
    <td>{{game.id}}</td>
    <td>{{game.name}}</td>
  </tr>
</table>
export class UpdateGameBodyComponent {
  public games: any = [];

  constructor(private httpClient: HttpClient) {
    httpClient.get('http://localhost:3000/api/games').subscribe(response => {
      this.games = response;
    });
  }

  updateGame(game) {

    this.httpClient.put('http://localhost:3000/api/games' + '/' + game.id, JSON.stringify({
        isRead: true
      }))
      .subscribe(response => {
        console.log(response);
      })
  }
};

当我单击更新按钮时,控制台会显示一个错误,指出它无法获取 Id 的值,我想解决这个问题,以便我可以继续使 put 请求工作。

标签: htmlangulartypescript

解决方案


在 HTML 中将 '$game' 更改为 'game' 因为 *ngFor 返回值而不是 DOM 事件

<button (click)="updateGame(game)" class="btn btn-default btn-sm">Update</button>

推荐阅读