【问题标题】:How to merge results in angular fire from array from references如何合并来自参考的阵列的角火结果
【发布时间】:2020-08-17 19:31:10
【问题描述】:

我有一个从 angularfire 检索到的引用数组

this.userIds$ = this.users$.switchMap(email =>
  db.list('/USERS/', ref => {
    let temp = email ? ref.orderByChild('EMAIL').startAt(email).endAt(email + "\uf8ff") : ref
    console.log('carrot');
    return temp;
  }
  ).snapshotChanges()
);

我试图将此数据作为一个可观察的数据返回,但是虽然我可以看到填充正确数据库引用的路径,但什么时候说完我的配置数组只包含几千个“未定义”条目我在做什么错误的?我尝试了各种方法,但结果总是一样,所以我将问题浓缩到下面,希望得到一些帮助

//Subscribe to the output of user ids, when we get a hit (delivered as an array of Observable DataSnapshot) loop through and subscribe to all the children of this location
    this.userConfigs$ = this.userIds$.pipe(
      switchMap(itemIds => {
        let configs = itemIds.map(itemId => {
          let pathOrRef = '/AIS/USERSAVEDCONFIGS/' + itemId.key;
          console.log('tomato');
          db.list(pathOrRef).snapshotChanges(['child_added']);
        });
        return configs;
      })
    );

然后我就开始了

this.userConfigs$.subscribe();

【问题讨论】:

  • configs 变量在switchMap 主体中声明。这就是为什么return configs 中的configs 可能未定义
  • 我应该在哪里申报?如果我删除 let configs = 语句并用 return 替换它,结果是一样的。
  • @Dazza move return configs; inside switchMap
  • @Kamran Khatti 我认为它已经在 switchmap 中了? (请原谅糟糕的代码格式,我已经更新了它)或者,你的评论中是否有明显的我遗漏的东西?
  • @Dazza 你在return 之前尝试过console.log(configs) 以确保它具有这些值吗?

标签: angular rxjs angularfire mergemap


【解决方案1】:

你传递给switchMap 的函数应该返回一个 Observable,你返回的是一个数组。我认为 TypeScript 编译器应该警告你。

如果我理解正确,您希望获取一个 itemId 数组,为每个项目进行数据库调用,然后返回一个 pathOrRef 数组。

如果是这样,这样的事情应该可以工作:

  1. 使用from() 一次发出一个userIds
  2. 使用map() 将项目转换为pathOrRef
  3. 使用switchMap() 进行数据库调用
  4. 使用mapTo()返回pathOrRef
  5. 使用toArray() 将发射放入数组中
this.userConfigs$ = this.userIds$.pipe(
  switchMap(itemIds => from(itemIds).pipe(
    map(itemId => `/AIS/USERSAVEDCONFIGS/${itemId}`),
    switchMap(pathOrRef => fakeDatabaseCall(pathOrRef).pipe(mapTo(pathOrRef)))
  )),
  toArray()
);

这是StackBlitz上的示例

【讨论】:

  • 谢谢,我看过stackblitz上的例子,对我的代码进行了修改,但我没有得到任何输出。 db 调用似乎有问题,如果我记录前面的步骤,我可以看到 pathOrRef 填充了路径等。我已将 switchmap 行更改为:switchMap(pathOrRef => db.list(pathOrRef).snapshotChanges(['child_added']).pipe(mapTo(pathOrRef))) 如果我订阅此位置,即...changes(['child_added']).subscribe() 和记录输出我得到数据但随后似乎无法进一步管道数据,因为订阅对象上不存在管道。
  • 为了清楚起见,是的,我想获取一个 itemIds 数组并对每个项目进行 db 调用到 firebase 位置,例如/AIS/USERSAVEDCONFIGS/123456/ 可能包含 0...n 个孩子。我希望这些不同地点的所有孩子都被送回!
猜你喜欢
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
相关资源
最近更新 更多