我有Angular 6
个应用程序和外部服务api
,每个请求最多返回50条记录。但是在某些情况下,我需要获得100条记录。
例如,以下请求将给我前50条记录:
www.example.com/records/?count=50
接下来的50个:
www.example.com/records/?count=50&lastID=FAKEID
是否有最佳实践以一种角度服务方法发送2个HTTP请求,但同时返回两个响应数据?
答案 0 :(得分:4)
您需要使用rxjs的forkJoin
import { forkJoin } from "rxjs/observable/forkJoin"; // Maybe import from 'rxjs' directly (based on the version)
...
public multipleRequestMethod() {
const firstCall = this.http.get('www.example.com/records/?count=50');
const secondCall = this.http.get('www.example.com/records/?count=50&lastID=FAKEID');
return forkJoin(firstCall, secondCall).pipe(
map([firstResponse, secondResponse] => [...firstResponse, ...secondResponse])
)
}
更多信息:Here
如果您想使用第一个请求的响应,则需要使用flatMap / switchMap
import { map, flatMap } from 'rxjs/operators';
...
public multipleRequestMethod() {
return this.http.get('www.example.com/records/?count=50').pipe(
flatMap(firstResult => {
return this.http.get('www.example.com/records/?count=50&lastID=' + firstResult[firstResult.length - 1].id).pipe(
map(secondResult => [firstResult, secondResult])
);
})
);
}