OSU222
OSU222

Reputation: 75

How to use use async and await to get return value from subscribe API call

I'm trying to use async and await to get the value returned from a subscribe API call. Currently, image and this.image are undefined the first time through the method then the second time it's called both defined properly. Am I doing something wrong or should I be doing this another way?

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

Upvotes: 0

Views: 171

Answers (1)

Naman Kheterpal
Naman Kheterpal

Reputation: 1840

async await work with promises. So you need to return promise form the function and the response will be to your variable as:

async showImageInTab(fileName) {
    const response = await this.getFile(fileName);
    const image = this.sanitizer.bypassSecurityTrustUrl(this.imageType +response['content']);
    console.log(image); // yuor image
  }
  getFile(fileName) {
    this.fileName = fileName;
   return this.organizationService.getFile(fileName).asPromise()
  }

Upvotes: 1

Related Questions