Search code examples
angularangular-httpclient

Run http service synchronously


I will get some response from below code:

this.http.post("http://localhost/angular5/user-add.php", this.myform.value, {responseType: 'json'}).subscribe(
            data => {
                console.log(data)
            }
        )

After getting the result, I need to run below code:

this.http.post("http://localhost/angular5/user.php", formData).subscribe(
            imageData => {
                console.log(imageData)
            }
        )

I need to run this code synchronously. How to make it synchronous? Now the secondary code is not waiting for the primary code.


Solution

  • The easiest is probably async/await, without getting into Rx territory (you might not wanna delve in there).

    async doSomething() {
       const req1 = await this.http.post("http://localhost/angular5/user-add.php", this.myform.value, {responseType: 'json'}).pipe(first()).toPromise();
    
       const req2 = await this.http.post("http://localhost/angular5/user.php", formData).pipe(first()).toPromise();
    
       console.log(req1, req2);
    }
    

    The async keyword basically makes the function-body behave like its synchronous. It will always return a promise, so you might need to await doSomething().

    Hope that makes sense.