Issue
I have this bit of code, which is not working as I wish.
The aim is to check if a file is found. If found, then display it. If not found, then download it & display it. I would like to use a promise resolving to the base64 image and use it in the src property.
The first time run is downloading the files, but doesn't display them. On the subsequent runs, if I directly call 'readAsDataURL' I can see the pics, but if i call 'getphoto' there's nothing displayed even if the files are here.
I'm pretty sure the issue is in the returning type of the 'getphoto' function, but i can't wrap my head into making it work.
Here's the code :
async getPhoto(id: string) {
this.file.checkFile(this.file.dataDirectory, id).then ( exist => {
if (exist) {
return this.file.readAsDataURL(this.file.dataDirectory, id);
} else {
this.httpService.downloadMedia(id).subscribe(img => {
this.createFile(id, img).then( () => {
return this.file.readAsDataURL(this.file.dataDirectory, id);
});;
});
}
}, (error) => {
if (error['message'] == 'NOT_FOUND_ERR') {
this.httpService.downloadMedia(id).subscribe(img => {
this.createFile(id, img).then( () => {
return this.file.readAsDataURL(this.file.dataDirectory, id);
});
});
}
})
}
async createFile(path: string, img: Blob) {
this.file.checkFile(this.file.dataDirectory, path).then(exist => {
if (!exist) {
this.file.writeFile(this.file.dataDirectory, path, img)
.then(result => {
})
} else {
}
})
.catch(errorCheck => {
this.file.writeFile(this.file.dataDirectory, path, img)
.then(result => {
})
})
}
html page side
<ion-img class="photo_card img-centered" [src]="photoB64 | async" (click)="openPhoto(photoB64)" > </ion-img>
ts controller side
this.photoB64 = this.fileService.getPhoto(''+this.nichoir.mediafiles[this.indexPhoto].id);
Solution
Angular uses Observable. So you need to use toPromise()
method to use async
and await
keywords correctly:
async getPhoto(id: string) {
let file;
try {
let exist = await this.file.checkFile(this.file.dataDirectory, id).toPromise();
console.log(`exist is: `, exist);
if (exist) {
file = this.file.readAsDataURL(this.file.dataDirectory, id).toPromise();
}
else {
let img = await this.httpService.downloadMedia(id).toPromise();
let result = await this.createFile(id, img).toPromise();
file = await this.file.readAsDataURL(this.file.dataDirectory, id).toPromise();;
}
}
catch(ex) {
let img = await this.httpService.downloadMedia(id).toPromise();
let result = await this.createFile(id, img).toPromise();
file = await this.file.readAsDataURL(this.file.dataDirectory, id).toPromise();;
}
}
Answered By - StepUp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.