I have been researching similar items without success and I realize that I need a better understanding of promises, but I am facing some challenges.
My project involves Ionic 4/Angular 8 with an Azure-based backend. I am trying to display images from Azure storage by appending a key to the URL.
In order to avoid repetitive code for checking the key, getting a new one if it's expired, and appending it to the URL on every page, I decided to create a service function for this purpose. However, the calling function does not seem to wait for the '.then' method, resulting in 'undefined' values (I think). Ideally, I just want the service to return a string.
Here is the service function I have:
async getStorageURLWithKey(url: string): Promise<string> {
const nowplus5 = addMinutes(Date.now(), 5);
console.log(nowplus5);
console.log(url);
console.log(this.azurekey);
if (!this.azurekey || isBefore( this.azurekey.Expires, nowplus5 )) {
console.log('Getting new Key');
const keyObj = await this.getAzureKeyServer().toPromise();
await this.saveAzureKeyStore(keyObj);
return url + keyObj.Key;
} else {
console.log('Key is valid' + this.azurekey.Expires);
const rval = new Promise<string>(function(res) {
res(url + this.azurekey.Key);
});
return rval;
}
}
My calling function looks like this:
getBizImg(): string {
console.log('GetBizImg');
if (this.business.Id) {
this.userService.getStorageURLWithKey(this.business.ImageURL).then((url) => {
console.log(url);
return url;
}, reject => {
console.log('Rejected:' + reject);
});
} else {
return '';
}
}
When I call the getBizImg function from ngOnInit, it returns 'undefined' before the 'console.log(url)' line.
Here's the ngOnInit code:
ngOnInit() {
const imageurl = this.getBizImg();
console.log(imageurl);
}
The call should ideally come from the HTML page:
<ion-content padding>
<ion-img [src]="getBizImg()" ></ion-img>
</ion-content>
Once I resolve this issue, I can uncomment the code in the HTML page to prevent an endless loop.
It seems like I need to make the getBizImg() function async and await the call to return a promise:
ngOnInit() {
this.getBizImg().then((wibble) => {
console.log(wibble);
});
}
Here is the updated getBizImg function:
async getBizImg(): Promise<string> {
console.log('GetBizImg ID= ' + this.business.Id);
if (this.business.Id) {
const url = await this.userService.getStorageURLWithKey(this.business.ImageURL);
console.log(url);
return url;
} else {
return '';
}
}
However, this approach does not give me the simple string needed for the HTML.
After trying some different approaches, including using the Angular async pipe, the issue persists with an endless loop. It seems like there might be a more fundamental error that I am missing.
Would appreciate any advice or suggestions to resolve this issue.