我正在從事一個個人專案,我有一項服務可以從 firebases 存盤中回傳一組影像。問題是當我訂閱 observable 時,我得到一個空陣列。當我打開陣列時,所有資料都在那里。問題是當我嘗試對未定義的陣列執行某些操作時(例如,console.log(myArray[0]) 未定義)。如果我是正確的,問題是 observable 是異步的,這就是我得到空陣列的原因。我的問題是,我該如何解決這個問題?
這里是服務
getImagesForChosenRestaurant(id: string): Observable<any> {
this.imageList = []
this.imageRef = ref(storage, `food/${id}`)
listAll(this.imageRef).then(res => {
res.items.forEach(item => {
getDownloadURL(item).then(url => {
this.imageList.push(url);
})
})
})
return of(this.imageList);
}
這是訂閱
ngOnInit(): void {
this.route.params.subscribe(params => {
this.restaurantService.getImagesForChosenRestaurant(params['id']).subscribe((foodPic: any) => {
this.foodImages = foodPic;
})
})
}
謝謝你的任何回答。
uj5u.com熱心網友回復:
嘗試這個:
async getImagesForChosenRestaurant(id: string): Promise<void> {
this.imageList = []
this.imageRef = ref(storage, `food/${id}`)
const list = await listAll(this.imageRef);
list.items.forEach(async item => {
const url = await getDownloadURL(item);
this.imageList.push(url);
})
return of(this.imageList);
}
uj5u.com熱心網友回復:
您可以使用.map
方法將您的專案陣列從 轉換listAll
為getDownloadURL
. 之后只需Promise.all()
與 rxjs 一起使用from
。
import { from, Observable } from "rxjs";
import { ref, listAll, getDownloadURL } from "firebase/storage";
getImagesForChosenRestaurant(id: string): Observable<string[]> {
const wrapperFn = async () => {
const imageRef = ref(storage, `food/${id}`);
const listAllResult = await listAll(imageRef);
const imagesDownloadUrlsPromises = listAllResult.items.map((item) =>
getDownloadURL(item)
);
return Promise.all(imagesDownloadUrlsPromises);
};
return from(wrapperFn());
}
uj5u.com熱心網友回復:
嘗試這個
getImagesForChosenRestaurant(id: string): Observable<string[]> {
const imageRef = ref(storage, `food/${id}`);
return from(listAll(imageRef)).pipe(
switchMap((res) => forkJoin(res.items.map(getDownloadURL)))
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507492.html
標籤:Google Cloud Collective 有角度的 火力基地 承诺 rxjs
上一篇:CSS媒體查詢沒有產生任何回應