从Angular中的API占位符JSON中删除数据



我试图使用angular删除单击的td,但它不起作用,没有返回任何内容,它只是获取数据。

这里是component.ts:

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
dataArray;
id;
constructor( private http:HttpClient) {
this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(
data =>{
this.dataArray = data
}
)
}
ngOnInit(): void {
this.delete
}
delete () {
this.http.delete('https://jsonplaceholder.typicode.com/posts/${id}')
.subscribe(() => this.id = 'Delete successful');
console.log(this.dataArray)
}
}

这是我的桌子:

<div class="table-list">
<table class="table">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Operations</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of dataArray;" index as i>
<td>{{item.title}}</td>
<td> <i class="fal fa-check-circle px-2"></i> <i class="fal fa-edit px-2"></i> <button><i class="fal fa-trash-alt" (click)="delete()"></i></button> </td>
</tr>
</tbody>
</table>

您必须将一个参数传递给您的删除函数:

delete (id: number) {
this.http.delete('https://jsonplaceholder.typicode.com/posts/' + id)
.subscribe(() => this.id = 'Delete successful');
console.log(this.dataArray)

}

在您的html上添加(click)="delete(item.id)

然后要从阵列中删除数据,您必须运行:

this.array = this.array.filter((d) => d.id !== id));