[RxJS] How To get the results of two HTTP requests made in sequence

switchMap can chain two HTTP requests together, creating one request based on the results of the first request.

But the result observable did not have the data of the first request, instead it only had access to the data of the second HTTP request.

If we would like to have both the data of the first HTTP request and deliver it together with the data of the second request, we could use a selector function (notice the second argument passed to switchMap):

 

复制代码
sequentialRequests() {

const sequence$ = this.http.get<Course>(
            '/courses/-KgVwEBq5wbFnjj7O8Fp.json')
    .switchMap(course => {
        course.description+= ' - TEST ';
        return this.http.put('/courses/-KgVwEBq5wbFnjj7O8Fp.json', course)
    },
    (firstHTTPResult, secondHTTPResult)  => 
               [firstHTTPResult, secondHTTPResult]);

sequence$.subscribe(
    values => console.log("result observable ", values) 
);
    
}
复制代码

 

Other example:

复制代码
//emit immediately, then every 5s
const source = Rx.Observable.timer(0, 5000);
//switch to new inner observable when source emits, invoke project function and emit values
const example = source.switchMap(() => Rx.Observable.interval(2000), (outerValue, innerValue, outerIndex, innerIndex) => ({outerValue, innerValue, outerIndex, innerIndex}));
/*
    Output:
    {outerValue: 0, innerValue: 0, outerIndex: 0, innerIndex: 0}
    {outerValue: 0, innerValue: 1, outerIndex: 0, innerIndex: 1}
    {outerValue: 1, innerValue: 0, outerIndex: 1, innerIndex: 0}
    {outerValue: 1, innerValue: 1, outerIndex: 1, innerIndex: 1}
*/
const subscribe = example.subscribe(val => console.log(val));
复制代码

 

posted @   Zhentiw  阅读(300)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示