I am trying to retrieve a list of dogs from a database. I want to retrieve the list of dogs as an Observable<Dog[]>. However when I call toArray() or use any other method to try convert the incoming stream to an array I either receive no data when calling the retrieveDogs(dogsId) method. How does one go about retrieving an Observable array instead of just an 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)
}
You could do that to retrieve your data:
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));
}
Simple demo here http://jsbin.com/sotunopocu/2/edit?js,console