switchMap返回一个项目

时间:2018-03-26 11:41:40

标签: javascript angular typescript firebase rxjs

我正在尝试使用switchMap运算符切换observable:

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);

我得到一个可观察的,而不是可观察的数组。

  

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

的数组

如何解决?

感谢。

1 个答案:

答案 0 :(得分: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);