【问题标题】:switchMap is returning one itemswitchMap 正在返回一项
【发布时间】:2018-09-04 13:08:08
【问题描述】:

我正在尝试使用 switchMap 运算符切换可观察对象:

return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, {
    query: {
      orderByChild: 'deleted',
      equalTo: false
    }
  })
  .map((locations:any)=>{
    console.log(JSON.stringify(locations,null,2));
    return locations.map(location=>{
      return location.$key;
    });
  }).flatMap(locations=>{
    return locations
  }).switchMap(location=>{
    console.log(location);
    return this.db.object(`Devices/${location}`)
  })
  .do(console.log);

我得到一个 observable 而不是 observable 数组。

我需要获取“this.db.object(Devices/${location})”的数组

如何解决?

谢谢。

【问题讨论】:

  • 您正在使用flatMap(locations => locations) 展平阵列。然后为每次发射调用switchMap 。
  • 感谢您的回复,,,,我颠倒了 switchMap 和 flatMap 的位置,它现在可以工作了,但我仍然有如何合并 flatMap 运算符发出的分离对象,实际上任何相反的flatMap的,你有什么想法

标签: javascript angular typescript firebase rxjs


【解决方案1】:

您可能希望forkJoin 可观察对象以使它们成为一次提交。你可以这样做:

return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, {
    query: {
      orderByChild: 'deleted',
      equalTo: false
    }
  })
  .map((locations:any)=>{
    console.log(JSON.stringify(locations,null,2));
    return locations.map(location=>{
      return location.$key;
    });
  }).switchMap(locationKeys =>{
    console.log(location);
    const locationObs = locationKeys.map((key) => this.db.object(`Devices/${key}`);
    return Observable.forkJoin(...locationObs);
  })
  .reduce((acc, location) => [...acc, location], []);
  .do(console.log);

【讨论】:

  • 谢谢你的回复,flatMap的反面是什么?
  • 我不确定你的意思。也许您正试图将每个位置键转换为可观察对象的单个发射?如果是这样,我会将第一个 map 更改为 switchMap,然后在该回调中返回 Observable.of(...locations.map(location=> location.$key) 并完全删除 flatMap。
  • 忘记我要做什么,只是一个问题,flatMap 发出单独的项目,对象--> 对象-->... 我需要的是与发出的 flatMap 相反数组中的一项 [obejct,object,...]
  • 如果您的 Observable 保证完成,那么您可以使用reduce,它“在源 Observable 上应用一个累加器函数,并在源完成时返回累积的结果,给定一个可选的种子值。” reactivex.io/rxjs/class/es6/…
猜你喜欢
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-15
相关资源
最近更新 更多