我是使用 RxJs 运算符的初学者,我需要一种方法,该方法从服务调用 5 个可观察量,它应该仅在第一个可观察量完成后从服务中获取数据,然后组合所有可观察量并转换为新的可观察量,并在函数中返回新的可观察量。下面的代码演示了该方案。
GetAllDetails(): Observable<AllDetails> {
const user = this.service.getUser() // Observable<User>
const firstDetails = this.service.getFirstDetail() // returns Observable<FirstDetail>
const secondDetails = this.service.getSecondDetail() // returns Observable<SecondDetail>
const thirdDetails = this.service.getThirdDetail() // returns Observable<ThirdDetail>
const fourthDetails = this.service.getFourthDetail() // returns Observable<FourthDetail>
// need to return a value that something compatible with Observable<AllDetails>
// so the logic should check if user info available then do combining all observable values and
// return as new observable
return of(new AllDetails(first, second, third, fourth)
}
我尝试使用CombineLate和switchMap,但是在第一次可观察完成之后,我无法实现这一点。如果有人可以帮助我,请表示感谢。
你可以试试这个:
return user.pipe(
last(), // Get the lastest value when the `user$` completes
switchMap(
user => conditionOnUser
? forkJoin({ first: firstDetails, second: secondDetails /* ... */ })
: of(null)
),
map(
detailsOrNull => !detailsOrNull
? false // No user info available
: new AllDetails(detailsOrNull.first, detailsOrNull.second /* ... */)
)
)
我相信您正在寻找的是forkJoin
.
forkJoin
是最简单的方法,当您需要等待多个HTTP请求解析时。
例:
public fetchDataFromMultipleSources(): Observable<any[]> {
let response1 = this.http.get(url1).subscribe((response) => {
let response2 = this.http.get(url2);
let response3 = this.http.get(url3);
return forkJoin([response1, response2, response3]);
});
return response1;
}