【问题标题】:RXJS operators not working with firebaseRXJS 操作员不使用 firebase
【发布时间】:2018-07-08 05:51:41
【问题描述】:

我将 RXJS 操作符与 firebase observable(distinct 和 filter)一起使用。 这是我的火力基地树 here。 这是我的代码:

  let places this.db.list(`users/${this.authProvider.getUID()}/visitedPlaces`,{
    query:{
      orderByChild:"googleId"
    }
  });
places.distinct((p)=>{ 
  console.log(p)
  return p.googleId;
}).
   subscribe((snap)=>{
      console.log(JSON.stringify(snap,null,2))
    },(err)=>{
      console.log(JSON.stringify(err,null,2))
    },()=>{
      console.log("completed");
    });

我正在尝试根据 googleId 区分 firebase 数据。 我没有收到任何错误,但不同的列表不起作用。

对此有何帮助或理由?谢谢。

【问题讨论】:

  • 你能定义“不工作”吗?怎么了?您的任何console.log 语句是否正在执行?
  • 两个日志都返回一个列表。但是,它们并没有区别。
  • 能否显示console.log(p)console.log(JSON.stringify(snap,null,2)) 的输出。
  • `[ { "纬度": 33.87628190799748, "经度": 35.53945333505702, "_isCurr": false, "googleId": "" }, {...},{...}.. .] 这个日志对于两者都是一样的
  • 日志应该是places 中每个项目的单个日志条目。听起来您是通过 distinct 运算符发送整个数组,而不是一次发送一个元素。

标签: angular typescript firebase firebase-realtime-database rxjs


【解决方案1】:

听起来您在数组而不是对象流上使用distinct 运算符。所以p 是您的 distinct 运算符中的一个数组,而不是您期望的数组内的对象。您可以使用 map 中的 vanilla js 来做到这一点,如下所示:

Rx.Observable.of([
  { id: 1},
  { id: 2},
  { id: 1},
  { id: 3},
  { id: 2}
]).map(x => x.reduce((a, c) => {
   if (!a.some(y => y.id === c.id)) {
      a.push(c);
   }
   return a;
  }, [])
).subscribe(x => { console.log(x); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>

或者你可以像这样使用flatMap 扩展数组:

Rx.Observable.of([
  { id: 1},
  { id: 2},
  { id: 1},
  { id: 3},
  { id: 2}
])
.flatMap(x => x)
.distinct(x => x.id)
.subscribe(x => { console.log(x); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>

【讨论】:

  • 感谢您的工作。但我需要显示的结局 x 不是异步的
  • 所以我不能使用异步管道来显示我需要存储在数组中的 x 值然后我显示它。
  • 你能解释一下如何对重复次数最多的数字进行排序。所以如果数字 2 重复 5 次,数字 1 重复 2 次,我需要显示 2 第一个数字
  • @KhaledRamadan 您可以对map 运算符中的数据进行任何转换。因此,如果您使用第一个解决方案,那么您只需在 map 运算符中的数组上执行 .sort(...) 即可。如果您使用的是第二个,则必须在订阅中构建数组。您可以在它进入时按顺序构建它,或者在完成回调中对其进行排序。
  • @KhaledRamadan 您可以使用异步管道而无需异步。只要它是可观察的,您就可以使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 2021-07-30
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多