【问题标题】:Angular 6 - Delete data from app.component.html and updating changes on viewAngular 6 - 从 app.component.html 中删除数据并更新视图上的更改
【发布时间】:2018-05-07 19:14:04
【问题描述】:

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

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

【问题讨论】:

  • 您基本上有两种选择:第一种由 Ashish Tanajan 介绍 另一种选择是从 API 重新加载数据(而不是重新加载视图)。您所做的选择将基于服务器端数据更改的频率以及用户拥有最新数据副本的重要性。

标签: javascript angular typescript angular6


【解决方案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));
}

【讨论】:

    【解决方案2】:

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

    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));
    }
    

    【讨论】:

    • 非常巧妙的解决方案
    【解决方案3】:

    只需将索引从 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 2016-06-09
      • 2018-12-25
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多