Issues arise when attempting to store data into an array with the assistance of FileReader

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.

Answer №1

Why are you choosing to convert it into base64 format? Instead, you can easily generate a URL from the blob using

const blobUrl = URL.createObjectURL(blob)
(just remember to revoke the URL to free up memory once it's no longer in use with URL.revokeObjectURL(blobUrl)). This method is more efficient.

However, the reason your code is not working as expected is due to a context problem (this does not refer to what you intended). Within the callback, the context is that of the reader object. The error message

Property 'images' does not exist on type 'FileReader'
suggests that this is actually an instance of FileReader.

Edit: It's also important to declare i using let in your loop; otherwise, i may not be what you anticipate within the callback function.

If you wish to maintain the outer scope context, consider utilizing an arrow function:

getImages(): void {
for (let i = 0; i < this.myData.length; i++) {
  this.myApiCalls.getImg()
    .subscribe(res => {
      var reader = new FileReader();
      reader.addEventListener("load", () => {
        this.images[i] = reader.result;
      });
      reader.readAsDataURL(res);
    },
      err => {
        console.log(err.message)
      });
  }
}

Answer №2

Give this updated code a try and see if it works for you.

images: any[]= [];

getImages(): void {
for (var i = 0; i < this.myData.length; i++) {
  this.myApiCalls.getImg()
    .subscribe(res => {
      this.readImageFile(i,res);
    },
      err => {
        console.log(err.message)
      });
  }
//checking console log to see if values are saved in array.
console.log("Print your Value here once",this.images);
}

readImageFile(indexVal:number,response: Blob): void {
      let self = this;
      var reader = new FileReader();
      reader.readAsDataURL(response);
      
      reader.onloadend = function () {
          self.images[indexVal] = reader.result;
        }
} 

Test this out and give me feedback on how it goes. I believe this will help resolve the issue you're facing. I have experience with similar functions before.

Thank you,

Muthukumar

Answer №3

Check out this insightful answer that could provide valuable information here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Saving a user with a BLOB avatar in Angular 5: Tips and Tricks for Success

As a newcomer to Angular, I am trying to figure out how to properly save a new user with an avatar. Can someone help me understand how to pass the Blob value of the avatar to my user Model for successful saving? Below is the code snippet I am working with ...

Using Angular 10 to make an HTTP POST request, with the goal of appending a string

Whenever I try to send a post request to an api endpoint, I keep encountering an error with status code 500. name: "HttpErrorResponse" ok: false status: 500 statusText: "Internal Server Error" Below is the code I am using: var selected ...

Angular2 Animation for basic hover effect, no need for any state change

Can anyone assist me with ng2 animate? I am looking to create a simple hover effect based on the code snippet below: @Component({ selector: 'category', template : require('./category.component.html'), styleUrls: ['./ca ...

Advantages of incorporating types through imports versus relying solely on declaration files in Typescript

We are currently in the process of switching from plain JavaScript to TypeScript. One aspect that I personally find frustrating is the need to import types. In my opinion, importing types serves no real purpose other than cluttering up the import section ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...

Encountered a syscall spawn git error while running npm install command

I recently attempted to execute npm install and encountered the following problems: Even after attempting to clear cache forcibly, installing git, and updating node, none of these solutions proved effective. Above is the specific error message I received ...

Angular's focus function poses certain challenges that need to be addressed

I am seeking assistance as a new programmer facing a beginner's challenge. I have two inputs and I would like to enter a series of numbers in the first input (DO) and have them automatically populate in the second input (communal code). Inputs: http ...

Issues encountered when trying to upload images to Firestore Storage

I am attempting to upload an image and store its URL in a Firestore document. To achieve this, I have the following code snippet: This function uses the device camera to capture the photo. selectImage(): Promise<any> { return new Promise(resolv ...

What is the reason behind Webpack's behavior of loading all files from a folder during lazy loading

I am attempting to dynamically import i18n files using webpack: function getI18n(lang) { return import(/* webpackChunkName "i18n/[request]" */ `./locales/${lang}.json`) .then(/*whatever*/) } However, I have noticed that all the files from the specifi ...

Angular 2 destroy outlet-content and refresh the view

Is there a method in Angular 2 to remove a component that was automatically created within a router-outlet? I am looking to destroy it so that a new one is generated when I navigate back to that outlet (or is there a way to reload the outlet?). ...

Why does my ng2 validator insist on enclosing my validation messages in the newline character ` `?

Following the error-text-accumulation pattern outlined in the angular2 documentation, I gather all messages from my custom form validators and combine them into a single string to present to the user: onValueChanged(data?: any) { if (!this.heroForm) { r ...

Angular is intercepting HTTP subscriptions without finalizing them

Within my code, I have a system in place where an interceptor is triggered to check for HTTP responses with the status code 401. If this code is detected, it initiates a request for a refresh-token by calling the method refreshToken(), before retrying the ...

Is NPM enterprise necessary for Angular2 and Java development?

Is an NPM enterprise version necessary if I plan to utilize Angular2 with Java as the backend technology for developing applications within my organization, without using Node JS or NPM server? ...

Unable to implement the `omega/theme.css` file within the angular.json configuration

"styles": [ "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css", "node_modules/primeicons/primeicons.css", ...

Tips for retrieving the generated ID from the server immediately following form submission using the Post method in TypeScript

When submitting a long-form, it is important to ensure that no data is lost. Users should be able to stay on the same page to make any necessary changes after clicking the submit button. I need to receive the unique id generated by the server upon submissi ...

React slick slider not functioning properly with custom arrows

"I have encountered an issue while trying to implement multiple sliders in my component with custom arrows positioned below each carousel. Despite following the documentation meticulously, the arrows do not respond when clicked. What could possibly be ...

The navigation bar overlays the background images

I'm struggling to adjust the positioning of my image so that it doesn't get hidden underneath my navigation bar. I want my background image to stay fixed while text scrolls over it, but I can't seem to figure out the correct height for my im ...

Changing the names of properties within a intricate JSON structure

I have a JSON data structure that is quite complex, like the one shown below: const json = '{"desc":"zzz", "details": { "id": 1, "name": "abc", "categoryDetails": { "cid": ...

Jest's expect method fails to capture errors thrown by async/await functions

I'm currently experimenting with a TypeScript-Express application that utilizes MongoDB and Mongoose. To perform testing, I have integrated jest and mongo-memory-server into the project. While I have succeeded in testing the insertion of new documents ...

Tips on using services for storing and fetching list data in Angular

I currently have two components, the "add-expense" component and the "view-list" component. The "add-expense" component collects expense details from a form and stores them as an object. My goal is to add this object to an empty list within the "expense-li ...