如何将ForkJoin用于HTTP请求的顺序Angular 4 [英] How to use ForkJoin for sequence of http requests Angular 4

查看:55
本文介绍了如何将ForkJoin用于HTTP请求的顺序Angular 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,可以进行两个http调用,第二个http的输入取决于第一个http响应,我需要同时返回两个结果.我有下面的代码会引发错误

I have a function which makes two http calls, the input of second http depends first http response and I need the two results to be returned at the same time. I have the below code which throws the error

SomeMethod(): Observable<any> {
    let firstResult;
    let secondResult;

    firstResult = http.get('////').map(data => {
        console.log('first response')
     secondResult = http.get('//// + {data.UserId}').map(response => {

        console.log('second response')
     })
    })

    return forkJoin([firstResult, secondResult]);
}

CallingMethod() {
    this.SomeMethod.subscribe(([firstResult, secondResult]) =>{
     /// Some logic
    })}

获取未定义的错误.期望可观察的,应允的或数组的.调试后知道第一个控制台输出正在打印后,第二个http调用将永远不会发出,也永远不会看到响应.

Getting error as undefined. Expected a observable, promise or array. After debugging got to know that first console output is printing, the second http call is never made and response is never seen.

如何使用forkJoin或任何其他机制一起返回两个嵌套的调用响应?

How to return two nested calls responses together using forkJoin or any other mechanism?

推荐答案

使用异步&等待控制多个http请求.

Use Async & await to control multiple http requests.

async SomeMethod(): Promise <any> {

    let firstResult;
    let secondResult;
    firstResult = await http.get('////').toPromise();
    secondResult = await http.get('//// + {res1.UserId}').toPromise();

    return forkJoin(firstResult, secondResult);
}

 CallingMethod() {
    this.SomeMethod().then(result => {
       /// Some logic
    });
 }

这篇关于如何将ForkJoin用于HTTP请求的顺序Angular 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆