是否可以在 Angular 中将 2 个 http 响应合并为一个?

Ark*_*adi 1 service http angular

我的Angular 6应用程序和外部服务api每个请求最多返回 50 条记录。但在某些情况下我需要获取 100 条记录。

例如,以下请求将为我提供前 50 条记录:

www.example.com/records/?count=50
Run Code Online (Sandbox Code Playgroud)

接下来的 50 名:

www.example.com/records/?count=50&lastID=FAKEID
Run Code Online (Sandbox Code Playgroud)

是否有任何最佳实践可以在一种角度服务方法中发送 2 个 HTTP 请求,但同时返回两个响应数据?

Ari*_*rif 5

需要使用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])
    )
}
Run Code Online (Sandbox Code Playgroud)

更多信息:这里

如果您想使用第一个请求的响应,那么您需要使用 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])
            );
        })
    );
}
Run Code Online (Sandbox Code Playgroud)