我有以下代碼,其中我從各種來源提取資料并在完成后設定加載標志。然而,目前維護起來相當麻煩。我該如何修復它?
constructor(
private courseContentFacade: CourseContentFacade,
private changeDetectorRef: ChangeDetectorRef
) {
this.courseContentFacade
.getUnsplashPhotos()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((unsplashPhotos) => {
this.unsplashPhotosLoaded = false;
if (unsplashPhotos) {
this.parseUnsplashPhotos(unsplashPhotos);
}
this.courseContentFacade
.getPexelsPhotos()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((pexelsPhotos) => {
this.unsplashPhotosLoaded = false;
if (pexelsPhotos) {
this.parsePexelsPhotos(pexelsPhotos);
}
setTimeout(
() => {
this.courseMediaItemsLoaded = true;
this.pexelsPhotosLoaded = true;
this.unsplashPhotosLoaded = true;
},
environment.production ? 2500 : 1000
);
});
});
}
uj5u.com熱心網友回復:
這是我如何將其重新設計為更慣用的 RxJS。這段代碼仍然嚴重依賴于全域狀態的使用。
整個應用程式對可變全域狀態的需求越少,維護和擴展就越容易。當涉及到 RxJS 時,這是 5 到 10 倍。
即便如此,使用高階運算子(在本例中為 mergeMap)可以大大減少此處創建的嵌套和復雜性:)
constructor(
private courseContentFacade: CourseContentFacade,
private changeDetectorRef: ChangeDetectorRef
) {
this.courseContentFacade.getUnsplashPhotos().pipe(
tap(_ => this.unsplashPhotosLoaded = false),
tap(unsplashPhotos => {
if (unsplashPhotos) {
this.parseUnsplashPhotos(unsplashPhotos);
}
}),
mergeMap(_ => this.courseContentFacade.getPexelsPhotos()),
tap(_ => this.pexelsPhotosLoaded = false),
tap(pexelsPhotos => {
if(pexelsPhotos) {
this.parsePexelsPhotos(pexelsPhotos);
}
}),
takeUntil(this.ngUnsubscribe),
delay(environment.production ? 2500 : 1000)
).subscribe(_ => {
this.courseMediaItemsLoaded = true;
this.pexelsPhotosLoaded = true;
this.unsplashPhotosLoaded = true;
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314761.html
標籤:javascript 有角的 打字稿 rxjs
下一篇:隱藏元素未正確定位
