Angular 6 - 从 app.component.html 中删除数据并更新视图中的更改

Angular 6 - Delete data from app.component.html and updating changes on view

我有一项服务正在获取数据列表并将其显示在 app.component.html

这是显示数据的代码:

<ul>
    <li *ngFor="let data of retrieveData"> 
        {{ data.id }} - {{data.title}} <span><button (click)="delete(data.id)">Delete Record</button></span>
    </li>
</ul>

如您所见,我为每行数据添加了一个删除按钮,然后调用一个方法从服务器中删除数据。

这有效,但同时我需要从视图中删除这些数据,而无需重新加载页面

在 app.component.ts 我有这个方法,然后调用服务方法:

delete() {
    this.apiService.delete(1).subscribe(result => {
      console.log(result);
    }, error => console.log('There was an error: ', error));
}

如何在不重新加载页面的情况下更新组件数据?

首先找到要删除的对象的索引,成功后,将其从已加载列表中删除..

delete(passedId) {
    this.apiService.delete(passedId).subscribe(result => {
      console.log(result);
      let indexOfId = this.retrieveData.findIndex((eachEleme) => {
          return eachElem.id = passedId;
      }); //gives the index of the first matching id
          // asuming you have unique ids..
      this.retrieveData.splice(indexOfId,1);  // removes the element
                                              // from the preloaded list
      this.retrieveData.a.findIndex()
    }, error => console.log('There was an error: ', error));
}

更新显示的集合以删除已删除的元素。

delete(id) {
    this.apiService.delete(id).subscribe(result => {
      console.log(result);
      this.retrieveData = this.retrieveData.filter((elem) => {
          return elem.id !== id;
      });
    }, error => console.log('There was an error: ', error));
}

只需将索引从 ngFor 传递到您的 delete() 函数,如下所示:

<ul>
    <li *ngFor="let data of retrieveData; let idx = index"> 
        {{ data.id }} - {{data.title}} <span><button (click)="delete(data.id, idx)">Delete Record</button></span>
    </li>
</ul>

然后在你的删除函数中

delete(id, idx) {
  this.apiService.delete(id).subscribe(result => {
    console.log(result);
  }, error => console.log('There was an error: ', error));
  this.retrieveData.splice(idx, 1);
}