如何将Observable流转换为Observable数组

时间:2017-04-27 04:03:07

标签: javascript angular reactjs typescript observable

我正在尝试从数据库中检索狗的列表。我想以Observable<Dog[]>的形式检索狗的列表。但是,当我调用toArray()或使用任何其他方法尝试将传入流转换为数组时,我在调用retrieveDogs(dogsId)方法时不会收到任何数据。如何检索Observable array而不仅仅是Observable stream

    retrieveDogs(dogIds : Array<string>): Observable<Dog[]>{
        return Observable.from(dogIds)
                .map(dogId => this.retrieveDog(dogId)) 
                .flatMap(dogObservable => dogObservable)
                .toArray();
     }

    retrieveDog(dogId : string) : Observable<DogEntity> {
     //afDB -> AngularFireDatabase that returns an observable with the data from the firebase database
        return this.afDB.object(DB_DOGS + DB_DASH + dogId)
                .map(dogObject =>DogEntity.convertObject(dogId,dogObject)
    }

1 个答案:

答案 0 :(得分:0)

您可以这样做来检索您的数据:

retrieveDogs(dogIds : Array<string>): Observable<Dog[]>{
  let obs = dogIds.map(dogId => this.retrieveDog(dogId));

  return Observable.forkJoin(obs);
}

retrieveDog(dogId : string) : Observable<DogEntity> {
  return this.afDB.object(DB_DOGS + DB_DASH + dogId)
    .map(dogObject => DogEntity.convertObject(dogId,dogObject));
}

这里的简单演示http://jsbin.com/sotunopocu/2/edit?js,console