【问题标题】:Angular 6 - Modifying Add Method to do Update on ViewAngular 6 - 修改添加方法以更新视图
【发布时间】:2018-05-07 21:48:04
【问题描述】:

我正在更改 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 上显示更改?

【问题讨论】:

    标签: javascript angular typescript angular6


    【解决方案1】:

    假设您想要的是在数组中找到其 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-28
      • 2018-12-25
      • 2015-11-20
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多