简体   繁体   English

Angular2中的Promise和Observable一起

[英]Promise and Observable together in Angular2

I am reading about Promise and Observable and I am not sure if my code is valid for angular2+ 我正在阅读有关Promise和Observable的内容,但不确定我的代码是否对angular2 +有效

I am using Promise with new http client 我在新的http客户端中使用Promise

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

Is this ok or bad example? 这个例子好不好?

Code looks okey but if your purpose is to use observable then you can use toPromise 代码看起来不错,但是如果您的目的是使用可观察的,则可以使用toPromise

this.http
.get('http://x.x.com/api/x/' + x + '/' + x + '/' + x + '', {
          headers: this.authenticationService.getAuthorizationHeader()
})
.toPromise()
.then()

Also in your code you are doing resolve() on error which is wrong to me, i would better call reject. 同样在您的代码中,您正在对我不对的错误执行resolve(),我最好将其称为拒绝。

Your code would make more sense lets say if you want to do retries or any other cool things, but if you need Promise then use toPromise. 如果您想进行重试或其他任何很酷的事情,您的代码将更有意义,可以说,但是如果您需要Promise,请使用toPromise。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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