angularangular4-httpclient

How to use ForkJoin for sequence of http requests Angular 4


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
    })}

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.

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


Solution

  • 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
        });
     }