首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 6 Async-await不能处理http请求

Angular 6 Async-await不能处理http请求
EN

Stack Overflow用户
提问于 2018-12-07 00:46:39
回答 1查看 14.7K关注 0票数 11

您好,我使用angular 6用下面的代码调用rest api。我正在尝试使代码与async-await函数同步。然而,有些东西遗漏了

代码语言:javascript
复制
async save() {

    if (this.changedRecords.length !== 0) {
          this.post('/api/devices/update-devices', this.changedRecords).
          then(x => { console.log("change"); console.log(`Resolved: ${x}`) });
    }
    if (this.newRecords.length !== 0) {
          this.post('/api/devices/new-devices', this.newRecords).
            then(x => { console.log("new"); console.log(`Resolved: ${x}`) });
    }
    if (this.deletedRecords != null) {
      this.post('/api/devices/delete-devices', this.deletedRecords).
        then(x => { console.log("deleted"); console.log(`Resolved: ${x}`) });
    }

}

  async post(url: string, list: DboDevice[]) {
    var result;
    if (list.length !== 0) {
      await this.http.post(url, list).subscribe(result => {
        result = true;
      }, error => {
        console.error(error);
        result = false;
      });
    }
    else {
      result = true;
    }
    return result;
  }

但是,当我运行此代码时,这些值在控制台中返回为"Resolved: undefined“。这让我相信await并没有停止post()函数中的程序。我在这里做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-07 00:58:39

Angular的this.http.post返回一个RxJS Observable。然后调用this.http.post(...).subscribe(...)返回RxJS Subscription对象。所以它们都没有返回Promise,所以你不能在await中使用它们。

如果您想在可观察对象中使用await,则必须使用toPromise()而不是subscribe(),后者返回一个Promise,该Promise由该可观察对象发出的第一个值解析(它在内部为您调用subscribe并将其包装在一个Promise对象中)。

代码语言:javascript
复制
await this.http.post(...).toPromise(value => {
  ...
});

https://github.com/ReactiveX/rxjs/blob/master/src/internal/Observable.ts#L342-L354

票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53656059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档