angularfire2数组操作

angularfire2数组操作,angular,firebase,Angular,Firebase,在firebase中处理阵列的正确方法是什么?我试图在单击按钮时切换数组或数字中的值。因此,每个数字只存在一次,比如说,单击按钮12,然后将12添加到firebase中的数组中,如果再次单击,则将其删除 这是我的代码,但是,它没有拼接,每次都会再次添加数字 blockTime(time: number) { const idx = _.indexOf(this.times, time); if (idx >= 0) { this.times.splice(idx, 1);

在firebase中处理阵列的正确方法是什么?我试图在单击按钮时切换数组或数字中的值。因此,每个数字只存在一次,比如说,单击按钮12,然后将12添加到firebase中的数组中,如果再次单击,则将其删除

这是我的代码,但是,它没有拼接,每次都会再次添加数字

blockTime(time: number) {
const idx = _.indexOf(this.times, time);
if (idx >= 0) {
     this.times.splice(idx, 1);
   } else {

  this.times.push(time);
   }
}

当您试图切换数组中的值时,请重新考虑您的数据结构。每当您执行
array.contains(…)
array.indexOf(…)
时,您可能应该使用类似集合的数据结构

由于JavaScript/JSON没有真正的集合,您通常(至少在Firebase上)通过使用具有
true
值的对象和设置项作为键来模拟它们。然后突然间,您的操作变得更加干净:

blockTime(time: number) {
  if (!this.times[time]) {
    this.times[time] = true;
  }
  else {
    delete this.times[time];
  }
}
或者如果您可以使用
false
值保留非阻塞时段:

blockTime(time: number) {
  this.times[time] = !(this.times[time] || false);
}
请注意,在Firebase中存储此类数据时,最好确保键是字符串,以避免Firebase SDK的数组强制。您只需在键前加上字符串即可,例如

blockTime(time: number) {
  var key = "time"+number;
  if (!this.times[key]) {
    this.times[key] = true;
  }
  else {
    delete this.times[key];
  }
}

当您试图切换数组中的值时,请重新考虑您的数据结构。每当您执行
array.contains(…)
array.indexOf(…)
时,您可能应该使用类似集合的数据结构

由于JavaScript/JSON没有真正的集合,您通常(至少在Firebase上)通过使用具有
true
值的对象和设置项作为键来模拟它们。然后突然间,您的操作变得更加干净:

blockTime(time: number) {
  if (!this.times[time]) {
    this.times[time] = true;
  }
  else {
    delete this.times[time];
  }
}
或者如果您可以使用
false
值保留非阻塞时段:

blockTime(time: number) {
  this.times[time] = !(this.times[time] || false);
}
请注意,在Firebase中存储此类数据时,最好确保键是字符串,以避免Firebase SDK的数组强制。您只需在键前加上字符串即可,例如

blockTime(time: number) {
  var key = "time"+number;
  if (!this.times[key]) {
    this.times[key] = true;
  }
  else {
    delete this.times[key];
  }
}

times
是firebase数组吗?是的,我得到的是这样的getDayTimes(day:string):FirebaseListObservable{const dayPath=
${this.basePath}/${day}
;this.times=this.db.list(dayPath);返回this.times;}splice将从数组中删除项,但不会从FirebasePath中删除该如何操作,如果您想将其从firebase中删除?请删除该项,然后推送新项
times
是firebase数组吗?是的,我得到的是这样的getDayTimes(day:string):FirebaseListObservable{const dayPath=
${this.basePath}/${day}
;this.times=this.db.list(dayPath);返回this.times;}splice将从阵列中删除项目,但不会从firebase中删除。如果您希望将其从firebase中删除,您会怎么做?删除项目,然后推送新项目嘿,伙计,我觉得这种方法很正确,可能我没有以正确的方式存储数据。您是否有firebase中数据结构的示例?我基本上有一个叫做schedule的节点,一周中的每一天都有一个子节点,时间就是我要解决的问题。提前感谢数据看起来像这里的
节点:嘿,伙计,我觉得这个方法很正确,也许我没有以正确的方式存储数据。您是否有firebase中数据结构的示例?我基本上有一个叫做schedule的节点,一周中的每一天都有一个子节点,时间就是我要解决的问题。提前感谢数据看起来像这里的
节点: