![](/img/trans.png)
[英]Using rxjs forkjoin and angular 10 http interceptor, how do I exchange only 1 refresh token with multiple http calls?
[英]How to make multiple HTTP calls in Angular6, using forkJoin and ngrx?
在我的angular6應用中,我有三個類別,catA,catB和catC。 每個類別都需要來自3個API的數據 。 單擊任何類別后,它將加載CategoryDetailsComponent,然后調度動作(LoadCategoryDetails)。
我已經實現了forjoin
來執行並行api調用(在服務中),還實現了resolver
以確保所有調用都已完成,然后才應加載該組件。
categoryNames
數組為空 CategoryNames
數組顯示上一類別(catA)的列表 也許其中一個api調用花費時間。 並且我的解析器配置不正確。
如何配置效果和解析器?
如何使用forkjoin進行多個調用並將數據發送到組件?
dipatch操作並訂閱選擇器
ngOnInit() { const id = parseInt(this.route.snapshot.paramMap.get('categoryId'), 10); this.store.dispatch(new fromCategory.LoadCategoryDetails(id)); this.store.select(getCategoryDetails) .subscribe((data) => { this.categoryDetails = data[0]; this.journeys = data[1]; this.categories = data[2]; }); // filter only category name // problem this.categories.forEach( category => { this.categoryNames.push(category.name); }); }
效果(尋找行動和電話服務)
@Effect() loadCategoryDetails$ = this.actions$.pipe( ofType<fromCategory.LoadCategoryDetails>(CategoryActionTypes.LoadCategoryDetails), switchMap((action) => { return this.categoryService.getCategoryDetails(action.payload).pipe( map(data => new fromCategory.LoadCategoryDetailsSuccess(data)) ); }) );
服務函數進行多個調用並使用forkjoin
import { forkJoin } from 'rxjs'; getCategoryDetails(categoryId) { const categoryDetails = this.http.get(url); const journeys = this.http.get(url); const courses = this.http.get(url); return forkJoin([categoryDetails, journeys, courses]); }
解析器
export class CategoryDetailsResolver implements Resolve<any> { constructor( private categoryService: CategoryService, private router: Router) {} resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { const categoryId = route.paramMap.get('categoryId'); return this.categoryService.getCategoryDetails(categoryId); } }
提前致謝。
重構代碼以不使用route.snapshot,看看是否可以解決。
ngOnInit() {
this.route.data.subscribe((data) => {
if(data) {
this.store.dispatch(new fromCategory.LoadCategoryDetails(data.id));
this.store.select(getCategoryDetails)
.subscribe((data) => {
this.categoryDetails = data[0];
this.journeys = data[1];
this.categories = data[2];
this.categories.forEach( category => {
this.categoryNames.push(category.name);
});
});
}
});
}
您對forkjoin的實現對我來說很好。 但是我可以在您的代碼中看到的一個問題是,您正在迭代getCategoryDetails回調之外的類別。 由於它是異步的,因此應始終確保在進行迭代之前獲取類別。 為此,您應該將用於迭代類別的代碼移至成功的回調函數。
ngOnInit() {
const id = parseInt(this.route.snapshot.paramMap.get('categoryId'), 10);
this.store.dispatch(new fromCategory.LoadCategoryDetails(id));
this.store.select(getCategoryDetails)
.subscribe((data) => {
this.categoryDetails = data[0];
this.journeys = data[1];
this.categories = data[2];
this.categories.forEach( category => {
this.categoryNames.push(category.name);
});
});
// filter only category name
// problem
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.