html - 执行 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)
})
}
我希望表格在我发布新游戏时自动更新。
解决方案
您没有取回更改的数据。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调用来更新数据。您可以使用它来初始加载数据以及在创建新游戏后进行更新。
推荐阅读
- .net-core - 如何在 Raspberry PI 上运行的 .NetCore C# 中使用 PocketSphinx?
- session - 跨任务窗格和对话框的会话 cookie
- php - Laravel Nova 找不到一些模型
- java - 用于运行和调试的 ByteBuffer 的不同行为
- python - 使用 for 循环重命名多个列(python)
- vhdl - 如何在保持向后兼容聚合的同时扩展记录类型?
- c - 链接器在 MINIX3.2.1 下抱怨未定义的引用
- facebook - 删除个人 Facebook Keep 开发者帐户
- .net - 如何使用 dotnet aries 框架内的中介代理连接两个超级账本 aries 边缘代理?
- c++ - 点云线搜索算法