首页 > 解决方案 > 执行 HTTP 发布后 HTML 表不会自动更新

问题描述

我为“游戏库”创建了一个虚拟网站,只是为了自学 http POST、GET、PUT 和 DELETE 方法,我的 api 有一个单独的文件,其中包含 3 个“游戏”。当我输入一个新的游戏名称并单击输入没有任何反应,但是当我刷新页面时,我的 html 表格会显示前三个游戏以及我刚刚发布的游戏。我想让它张贴然后立即显示在桌子上,而不是因为我认为它有点草率而不得不刷新页面。

我曾尝试将输入框放在表格上方,但我真的不知道还能尝试什么。

  <h3>Here is your list of current games in your library</h3>
<table>
  <tr>
    <th>Id</th>
   <th>Name</th>
 </tr>
 <tr *ngFor="let game of games">
   <td>{{game.id}}</td>
   <td>{{game.name}}</td>
 </tr>
</table>


public games: any = [];
     private url = 'http://localhost:3000/api/games';


 constructor(private httpClient: HttpClient){
     httpClient.get(this.url).subscribe(response => {
     this.games = response;
     });
 }

createGame(name: HTMLInputElement) {
    let post = {name :  name.value};
    name.value = '';
    let headers = new HttpHeaders();
    headers= headers.set('Content-Type', 'application/json');

    this.httpClient.post(this.url, {id: this.games.length + 1,name: post.name }, {headers})
    .subscribe(response => {
         console.log(response)

    })

}

我希望表格在我发布新游戏时自动更新。

标签: htmlangularapipost

解决方案


您没有取回更改的数据。POST调用成功后,进行GET调用以获取更新的数据。

createGame(name: HTMLInputElement) {
    let post = {name :  name.value};
    name.value = '';
    let headers = new HttpHeaders();
    headers= headers.set('Content-Type', 'application/json');

    this.httpClient.post(this.url, {id: this.games.length + 1,name: post.name },{headers}).subscribe(response => {
         console.log(response)
         // Subscribe back the changes
         this.httpClient.get(this.url).subscribe(response => {
             this.games = response;
         });
    })

}

另一种方法是编写另一个函数,该函数使用GET调用来更新数据。您可以使用它来初始加载数据以及在创建新游戏后进行更新。


推荐阅读