简体   繁体   中英

How to make a function to wait until asynchronous function (http post request) to complete in angular 2?

I have a function which depends on the response of http post request function. But because os post request as asynchronous, the function get executes before get post request response. So am getting error.

Can anyone give solution to make wait function until post request complete in angular 2?

Thanks in advance.

for example, if you have one function which makes service call and you want to call one more function after that service call is executed successfully so you need to call the second function in the .susbcribe of the first function like this

this.serivce.servcefunction(yourrequest).subscribe
(data => 
{
secondfunctiontoexecute();
},
Error => 
{
alert("failed")
})

The post request returns an Observable, so you need to subscribe to that Observable.

let post = {JSON to POST};

this.http.post(this.url, JSON.stringify(post))
    .subscribe(response => {
        functionToExecute()
     },
     (error: Response) => {
         if (error.status === STATUS_ERROR) {
             handleExpectedError();
         } else {
             handleUnexpectedError();
         }
});

You should extract a reusable error handling method, so you dont have to write the same code to the different http errors in every POST request you write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM