最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular2 http.post: Create promise with subscribe - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Jul 8, 2017 at 16:49 Andre PaviniAndre Pavini 3534 silver badges20 bronze badges 2
  • 2 Don't .subscribe, .map then convert it .toPromise(). Or just use the observable. – jonrsharpe Commented Jul 8, 2017 at 16:52
  • With .map and subscribe you are using Observable, it is a process asyncronous, you can use *ngIf for show the data in template – alehn96 Commented Jul 8, 2017 at 17:02
Add a ment  | 

2 Answers 2

Reset to default 5

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

Andre, you want to use the toPromise operator to transform the observable returned by .map() into a promise. Return the result of that operator

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

Now a proper promise is returned, so the calling code can use it as such:

postToPaymentApi(...).then(
    data => console.log(data)
)
发布评论

评论列表(0)

  1. 暂无评论