【问题标题】:Best way to update UI when the user removes an item in the database in Angular当用户在 Angular 中删除数据库中的项目时更新 UI 的最佳方法
【发布时间】:2019-02-01 12:17:05
【问题描述】:

我想知道当用户删除数据库中的项目时更新用户界面的最佳方式。我有以下场景:在用户界面中,我有地址绑定到组件中的一个数组,这个数组是根据数据库上的数据分配的。当用户单击“删除”按钮时,我执行 http 请求以删除数据库中的项目,但是当然,用户界面不会更新。如果我可以使用 router.navigate() 会很容易,这样组件刷新自身。但是当我导航到相同的路线时,角度不会重新加载/刷新组件。我能想到的唯一解决方案是编写一些打字稿代码来从数组中删除项目。

我的模特:

 export class Address {

  public id: number; //unique id I can use to remove the item
 ...
  }

我的组件的相关代码。

addresses: Array<Address>;

....

 removeAddress(id: number) : void {

//service used to make http requests, I pass the id to delete
this.addressService.removeAddress(id).subscribe((res) => {

     //How can I update the UI on Success?

},    (err: HttpErrorResponse) => {
  console.log(err);
});

【问题讨论】:

    标签: typescript angular7


    【解决方案1】:

    如果响应没有错误(HTTP 200),只需从数组中删除该项目。这将为用户节省流量。但是你也可以从数据库中重新加载剩余的项目。

    delete myArray[key];
    
    
    
    const index = myArray.indexOf(key, 0);
    if (index > -1) {
       myArray.splice(index, 1);
    }
    

    【讨论】:

    • 您的回答让我有了新的可能性。这就是我想要的!
    • 我更喜欢第二个选项。我只需要通过调用用于在组件初始化时填充地址的函数来重新分配地址数组。我没有想过这个选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多