首页 > 解决方案 > 使用承诺删除后如何刷新我的列表

问题描述

在我的 Angular 应用程序中,我想在删除后更新列表,但我不知道如何使用 promise

  delete(id: any) {
    this.missionService.deleteMission(id);
    // .then((res) => {
    //   this.missionsArray$[id] = null;
    //   this.missionsArray$ = this.getAllMissions();
    // }).catch((error) => {
    //   console.log('error', error);
    // });
  }

我尝试使用带注释的代码,它可以工作,但是使用相同的数据使我的列表翻倍(没有删除的项目)

我使用这个函数来构建我的列表:

  getAllMissions(): any {

    this.missionService.readAllMissions().then(response => {

      response.forEach(mission => {
        if (mission.data.missionCreator === this._auth.user.id) {
          mission.data.id = mission.ref['@ref'].id;
          this.missionsArray$.push(mission.data);
        } else {
          this.missionsArray$ = [];
        }
      });
    });
  }

以及删除一项的此功能:

  delete(id: any) {
    this.missionService.deleteMission(id);
    // .then((res) => {
    //   this.missionsArray$[id] = null;
    //   this.missionsArray$ = this.getAllMissions();
    // }).catch((error) => {
    //   console.log('error', error);
    // });
  }

我尝试使用带注释的代码,它可以工作,但是使用相同的数据使我的列表翻倍(没有删除的项目)

你能解释一下如何使用 Promise 进行体面的刷新吗?

标签: angularpromisefetch

解决方案


this.missionsArray$ = []在重新加载之前清空数组。

delete(id: any) {
    this.missionService.deleteMission(id);
     .then((res) => {
       this.missionsArray$[id] = null;
       this.missionsArray$ = []
       this.getAllMissions();
     }).catch((error) => {
       console.log('error', error);
     });
  }

或者你可以splice现有的数组

delete(id: any) {
    this.missionService.deleteMission(id);
     .then((res) => {
      this.missionsArray$[id] = null;
      for (var i = 0; i < this.missionsArray$.length; i++) {
        if (this.missionsArray$[i].id == id) {
          this.missionsArray$.splice(i, 1)
        }
      }
    }).catch((error) => {
      console.log('error', error);
    });
  }

推荐阅读