Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 http.post: Create promise with subscribe

I´m trying do create a function, that returns a Promise as the code: (someprovider.ts)

postToPaymentApi(url:string, data:string, options:RequestOptions, order:Order):Promise<any>{
let result =  this.http.post(url, data, options).map(res => res.json())
  .subscribe(data => {
    // all my logic here!
    });
  }, error => {
    console.log(error)
  })

  return new Promise((resolve)=>{
    resolve(result)
  })

}

The problem is, when I call this function, I do not get the data, because this post take a few seconds to finish and I get the promise before the post finish.

this.postToPaymentApi(url, data, options, order).then(data => {
    console.log(data);
  })

What Am I doing wrong?

like image 504
Andre Pavini Avatar asked Apr 07 '26 15:04

Andre Pavini


1 Answers

if you want to create a function that return promise, your function should be :

postToPaymentApi(url:string, data:string, options:RequestOptions, order:Order):Promise<any >{
   return new Promise((resolve, reject) => {
          this.http.post(url, data, options)
           .map(res => res.json())
           .subscribe(data => {
             resolve(data);
            }
           }, error => {
             console.log(error)
             reject({error: error});
           });
        });
}
like image 159
Mankeomorakort Avatar answered Apr 09 '26 05:04

Mankeomorakort



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!