1

我有一项服务正在获取数据列表并将其显示在 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));
}

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

4

3 回答 3

1

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

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));
}
于 2018-05-07T19:21:03.140 回答
1

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

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));
}
于 2018-05-07T19:26:37.543 回答
1

只需将 index 从 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);
}
于 2018-08-03T09:57:14.977 回答