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

标签 angular http service

我有 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/

相关文章:

angularjs - 导航嵌套组件时创建面包屑 (Angular 2)

java - 广播接收器即使在应用程序被用户杀死后也能正常工作

android - 是否可以在一个地方托管 aidl 文件?

javascript - 带有自定义标签的 Mapbox GL Popup 设置内容

node.js - ionic 2 : Test with jasmine and karma error 'ng test'

google-chrome - Chrome 扩展 : how to intercept requested urls?

javascript - 跨域 AJAX 请求未被阻止 : is this a security vulnerability?

javascript - 从一个 Controller 设置到要在另一个 Controller 上使用的服务的值在使用 Angular js 刷新页面时不返回任何值(Angular 的新功能)

html - 将 String 附加到 ngModel 以获取表达式

javascript - 前端对HTTP了解多少?