I am currently working on an Angular4 project where I am facing an issue with saving Blob data returned from my API call to an array of pictures in base64 format. This is so that I can later display the images using *ngFor
.
Here is the API call I am making:
getImg(): Observable<Blob> {
const path = *can't show this part*;
return this.http.get(path, { responseType: "blob" });
}
And here are the approaches I have tried:
The function encounters an error at line this.images[i] = reader.result;
, indicating
Property 'images' does not exist on type 'FileReader'
.
images: Array<any> = [];
getImages(): void {
for (var i = 0; i < this.myData.length; i++) {
this.myApiCalls.getImg()
.subscribe(res => {
var reader = new FileReader();
reader.readAsDataURL(res);
reader.addEventListener("loadend", function () {
this.images[i] = reader.result;
});
},
err => {
console.log(err.message)
});
}
}
Another attempt was made using callbacks, but it resulted in a different error message stating
'this' implicitly has type 'any' because it does not have a type annotation.
getImages(): void {
for (var i = 0; i < this.myData.length; i++) {
this.myApiCalls.getImg()
.subscribe(res => {
this.readImageFile(res, function(e: any) {
this.fields[i] = e.target.result;
});
},
err => {
console.log(err.message)
});
}
}
readImageFile(response: Blob, callback: any): void {
var reader = new FileReader();
reader.readAsDataURL(response);
reader.onloadend = callback
}
Although the data is being retrieved correctly, I am struggling to store it in the array. Any help or guidance on resolving this issue would be greatly appreciated. Thank you.