我有 Angular 6
应用程序和外部服务 api
,每个请求最多返回 50 条记录。但在某些情况下,我需要获取 100 条记录。
例如,以下请求将给我前 50 条记录:
www.example.com/records/?count=50
接下来的 50 个:
www.example.com/records/?count=50&lastID=FAKEID
是否有任何最佳实践可以在一种 Angular 服务方法中发送 2 个 HTTP 请求,但同时返回两个响应数据?
最佳答案
需要使用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])
);
})
);
}
关于angular - 是否可以在 Angular 中将 2 个 http 响应合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54887944/