Angular 6 - 修改添加方法以在视图上进行更新

Angular 6 - Modifying Add Method to do Update on View

我正在更改 app.component.html

上显示的数据列表
<ul>
<li *ngFor="let data of DataSource"> 
        {{ data.id }} - {{data.title}} 
</li>
</ul>

我已经像这样推送了一个新的数据行:

  create() {
    const newPostId = this.postId + 1;
    this.apiService.create(newPostId, this.postTitle, this.postText).subscribe(result => {
      const newId = result['id'];
      this.retrieveData.push({id: newId, title: this.postTitle});
      this.dataCount = this.dataCount + 1;
    }, error => console.log('There was an error: ', error));
  }

这很好用,并在数据列表的末尾添加了一个新行。

我的问题是:

如何修改我的 create() 方法以更新电流并在 app.component.html 上显示更改?

假设您想要在数组中找到其 ID 与您正在更新的项目匹配的项目,并将其替换为新项目,您将执行如下操作:

this.apiService.update(...).subscribe(result => {
  const newId: number = result['id'];
  const currentItemIndex = this.retrieveData.findIndex((item: {id: number}) => item.id === newId);
  if (currentItemIndex > -1) {
      // replace the current item with the new one
      this.retrieveData.splice(currentItemIndex, 1, {id: newId, title: this.postTitle});
  } else {
     // TODO: if it wasnt there to being with, is this an error?
  }
}, error => console.log('There was an error: ', error))