Angular 6 Async-await不适用于http请求

Jos*_*bor 8 async-await rxjs angular-promise angular angular6

您好,即时通讯使用angular 6使用以下代码调用rest api。我试图使代码与async-await函数同步。但是缺少什么

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;
  }
Run Code Online (Sandbox Code Playgroud)

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

mar*_*tin 13

Angular的this.http.post返回RxJS Observable。然后调用this.http.post(...).subscribe(...)返回RxJS Subscription对象。因此,它们都不返回Promise,因此您不能将它们与一起使用await

如果您希望能够await与Observable 一起使用,则必须使用它toPromise()而不是subscribe()返回一个Promise,该Promise将使用该Observable发出的第一个值进行解析(它在内部调用subscribe您并将其包装为一个Promise对象)。

await this.http.post(...).toPromise(value => {
  ...
});
Run Code Online (Sandbox Code Playgroud)

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

  • 同样,对于在此之后也遇到尝试输出错误的问题的人,我可以通过添加.catch(error => {console.log(error)})使它起作用。在toPromise()的结尾 (3认同)