我有一個問題——這對你來說似乎很明顯,但我想不通。
getCategoryID() 和 getRecipeList()
第一個從 API 獲取category陣列串列,第二個函式使用此串列發送(n = 陣列長度)關于recipes.
最后,我想要一個陣列:類別名稱 配方名稱
問題是兩者都使用訂閱。由于它們是異步的,函式執行太快。嘗試使用await- 但它回傳給我一個Promise. 我希望第一個函式等待 api 到 api 查詢并將資料傳遞給第二個,而不是 promise
getCategoriesFromAPI() {
this.apiService.getCategories().subscribe(data => {
console.log(data);
});
}
getRecipesFromAPI() {
this.apiService.getRecipes(categoryID).subscribe(data => {
console.log(data);
});
}
uj5u.com熱心網友回復:
查看 RXJS 管道。它們可以幫助您處理不同的 observables。在你的情況下,我認為你正在尋找這樣的東西:
this.apiService.getCategories().pipe(
switchMap((categories) => forkJoin(
categories.map((category) => this.apiService.getRecipes(category.id))
))
).subscribe((recipes) => {
// This should return array of arrays [[recipe, recipe, recipe], [recipe, recipe]]
console.log(recipes);
})
https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin
https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421064.html
標籤:
