Angular2 http.post: Create a subscription promise

I am trying to create a function that returns a Promise as 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 that when I call this function, I am not getting data because this post takes a few seconds and I get the promise before the post ends.

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

      

What am I doing wrong?

+3


source to share


2 answers


if you want to create a function that returns a 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});
           });
        });
}

      

+4


source


Andre, you want to use toPromise

operator
to convert the observable returned .map()

to a promise. Return the result of this operator

return http.post(...).map(...).toPromise()

      



The correct promise is now returned, so the calling code can use it as such:

postToPaymentApi(...).then(
    data => console.log(data)
)

      

+3


source







All Articles