gpt4 book ai didi

javascript - 如何将 Observable 流转换为 Observable 数组

转载 作者:行者123 更新时间:2023-11-28 04:42:27 25 4
gpt4 key购买 nike

我正在尝试从数据库中检索狗的列表。我想检索狗的列表为 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)
}

最佳答案

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

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

关于javascript - 如何将 Observable 流转换为 Observable 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43648449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com