无法从打字稿

时间:2019-06-22 11:46:07

标签: typescript firebase google-cloud-firestore ionic4

我正在使用以下代码从Firebase检索对象列表。我需要从列表中删除一个项目,但我的索引始终为-1。我在这里做什么错了?

filterItineraries(filters: any): any {
  let num = 0;
  this.allItineraries = [];
  this.filteredItineraries = [];

  for (let i = 0; i < 2; i++) {
    if (i === 0) {
      num = 0;
    } else {
      num = (filters.numberOfDays - 1);
    }

    const query = this.dataSvc.getAllItineraries()
        .where('destination', '==', filters.destination)
        .where('dateRange', 'array-contains', filters.dateRange[num]);

    query.get()
        .then(itineraryListSnapshot => {
          this.allItineraries = [];

          itineraryListSnapshot.forEach(snap => {
            this.allItineraries.push({
              id: snap.id,
              jobCode: snap.data().jobCode,
              destination: snap.data().destination,
              startDate: snap.data().startDate,
              endDate: snap.data().endDate,
              workDetails: snap.data().workDetails,
              userId: snap.data().userId
            });

            const index: number = this.allItineraries.indexOf(filters.id);

            if (index !== -1) {
              this.allItineraries.splice(index, 1);
            }

            console.log('index', index);
            console.log('filters.id', filters.id);
            console.log('filteredItineraries',  this.allItineraries);
          });
        });
  }
}

console.log console.log

我也尝试过将它移到for循环之外,但是index = -1。

最后我尝试了:

this.filteredItineraries = this.allItineraries;
const index: number = this.filteredItineraries.indexOf(filters.id);

if (index !== -1) {
  this.filteredItineraries.splice(index, 1);
}

console.log('index', index);
console.log('filters.id', filters.id);
console.log('filteredItineraries',  this.filteredItineraries);

索引始终= -1

1 个答案:

答案 0 :(得分:2)

此行没有执行您想要的操作:

const index: number = this.allItineraries.indexOf(filters.id);

index在这里始终是-1,因为allItineraries是对象数组,而filters.id是(从控制台输出的外观来看)字符串。 / p>

您需要自己遍历allItineraries来找到条目ee.id === filters.id处(您现有的比较是e === filters.id)。


不过,为什么不使用filtermap方法呢?

this.allItineraries = itineraryListSnapshot
        .filter(snap => snap.id !== filters.id)
        .map(snap => { id: snap.id, ...snap.data() });

我还使用了object spreadis supported in TypeScript >= 2.1语法。