我正在阅读有关 Promise 和 Observable 的内容,我不确定我的代码是否对 angular2+ 有效
我正在将 Promise 与新的 http 客户端结合使用
return new Promise((resolve) => {
this.http
.get('http://x.x.com/api/x/' + x + '/' + x + '/' + x + '', {
headers: this.authenticationService.getAuthorizationHeader()
})
.subscribe(
(data: any) => {
resolve(data.map((row) => {
return new Candlestick(row.time, row.open, row.high, row.low, row.close, row.volume)
}));
},
(error: HttpErrorResponse) => {
if (error.error instanceof Error) {
console.log('An error occurred:', error.error.message);
} else {
console.log(`Backend returned code ${error.status}, body was: ${error.error}`);
}
return resolve();
});
});
这个例子是好还是坏?
最佳答案
代码看起来不错,但如果您的目的是使用 observable,那么您可以使用 toPromise
this.http
.get('http://x.x.com/api/x/' + x + '/' + x + '/' + x + '', {
headers: this.authenticationService.getAuthorizationHeader()
})
.toPromise()
.then()
此外,在您的代码中,您正在对错误执行resolve(),这对我来说是错误的,我最好调用拒绝。
如果您想要重试或任何其他很酷的事情,您的代码会更有意义,但如果您需要 Promise,则使用 toPromise。
关于angular - Angular2 中的 Promise 和 Observable 结合在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56471137/