如何使用async和await从subscribe API调用获取返回值

时间:2018-05-01 13:06:53

标签: javascript angular typescript

我尝试使用async和await来获取订阅API调用返回的值。目前,image和this.image在第一次通过该方法时是未定义的,然后第二次被称为正确定义。我做错了什么或者我应该采取另一种方式吗?

  async showImageInTab(fileName) {
    const image = await this.getFile(fileName);
    console.log(image);
    console.log(this.image);
  }
  async getFile(fileName) {
    this.fileName = fileName;
    this.organizationService.getFile(fileName).subscribe(
      response => {
        this.image = this.sanitizer.bypassSecurityTrustUrl(this.imageType + response['content']);
        return this.sanitizer.bypassSecurityTrustUrl(this.imageType + response['content']);
      },
      err => console.error(err)
    );
  }

1 个答案:

答案 0 :(得分:1)

async等待与promises合作。所以你需要从函数中返回promise,响应将变为你的变量:

import re

t = 'x - 3x -7x+9-2x-12 = 42'
t = t.replace(' ','')
if ((t[0]) != '-' and not t[0] == '+'): #add trailing plus if necessary
    t = '+'+t
print(t)

print(re.findall(r"([+-]+(\d+)+[x])", t))