AngularJS promise fails to resolve when attempting to read a file using the FileReader

Can someone assist me with a function I am trying to create in my service? I want the function to use FileReader to read a small image file and return the result in a promise to my controller. The issue is that while the file reaches the service without any problem, it only logs a blank line when it gets to the controller. I believe the problem lies within how I am handling promises in this situation. Any ideas on what I am doing wrong?

Here is the code for the service function:

this.fileRead  = function(file) {
    var deferred = $q.defer();

    var reader = new FileReader();
    reader.readAsDataURL(file);

    deferred.resolve(reader.result);

    return deferred.promise;
};

And here is the code for the controller function:

$scope.onFileSelect = function($files) {
     MyService.fileRead($files[0])
                  .then(function(result) {
                    console.log(result);
                 });
};

Answer №1

There is no onload event specified in your code, which means it will not return the data read from the file.

this.readFile = function(file) {
    var promise = $q.defer();

    var reader = new FileReader();

    reader.onload = function() {
        promise.resolve(reader.result);
    };

    reader.readAsDataURL(file);

    return promise.promise;
};

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

Issues with Grunt functionality after installation on Ubuntu

I successfully installed Grunt by running the following commands in the terminal: sudo apt-get install nodejs sudo apt-get install npm npm install -g grunt-cli After executing npm install -g grunt-cli, here is the output from the terminal: (output he ...

HTML code is not displayed within the ng-template

After passing JSON data in the correct format from my Laravel controller, I'm trying to display it recursively using Angular. However, the HTML inside ng-template is not being rendered. What could be the issue? Note: I've replaced the default An ...

The submission of an Angular form results in errors such as being unavailable or

After building a registration page component in Angular and following tutorials, I encountered a frustrating bug. When pressing the submit button on the form, the console would display "undefined" when attempting to access the NgForm's value. However, ...

Jquery not populating table as anticipated

I am having an issue with populating a table using a JSON file. The first row works fine, but the subsequent rows are not showing up. Can someone please help me identify what I am doing incorrectly? Is my looping structure flawed? Thank you for your assi ...

JavaScript error message stating that the setAttribute function is null

As a newcomer to JS, I am currently working on creating a task list webpage that allows users to submit projects and create task lists within each project with designated due dates. In order to generate unique ID tags for projects and tasks, I utilized UU ...

I'm trying to figure out the best spot within this Mean.js application to insert the Angular code that will allow for sorting of

After receiving guidance from @Pavlo to utilize https://github.com/angular-ui/ui-sortable, I have a repetitive list that I am looking to make sortable. <div ui-sortable ng-model="regions" class="list-group region-list"> <a data-ng-repeat="re ...

Ways to include additional details in each row of an autocomplete feature

I have successfully implemented autocomplete for venues worldwide, but now I want to display the address of each venue below its name. For example, if the autocomplete suggests the venue name as ABCD, I want the address of that venue to appear right benea ...

Retrieve the selected value from a radio button

I am attempting to display the chosen value in an input field when a radio button is selected. However, the functionality seems to be broken when I include bootstrap.min.js. You can find the code on JSFiddle. $('input:radio').click(function() ...

The animation of a disappearing div with CSS is not stopping when hovering over it

Hello, I've been working on a snackbar feature that appears and disappears on a set timer but also needs to pause when hovered over. Unfortunately, the current setup with setTimeout and useState is causing issues with this functionality. I have looke ...

Trouble with card alignment in Bootstrap

I've been experimenting with creating a grid layout using cards and utilizing ng-repeat for generating the cards. Unfortunately, I'm running into an issue where there is no spacing between each card, as depicted in the image. https://i.stack.img ...

When attempting to install material UI in my terminal, I encounter issues and encounter errors along the way

$ npm install @material-ui/core npm version : 6.14.4 Error: Source text contains an unrecognized token. At line:1 char:15 $ npm install <<<< @material-ui/core CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException ...

What seems to be the issue with loading this particular file into my JavaScript code?

When attempting to import a file into my code, I encountered an issue where the folder could not be found. Interestingly, when manually typing out the folder name, it is recognized and suggested by the system. Even providing the full path did not yield dif ...

Access scope information when clicking with ng-click

I am currently using a php api to update my database, but I want the ability to choose which item gets updated with ng-click. app.controller('ReviewProductsController', function ($scope, $http) { $scope.hide_product = function () { ...

Switch between two AppBars simultaneously while scrolling in Material UI

In my Header.js component, I have two AppBars. The first one is sticky and the second one is not initially visible. As we scroll down, I want the second AppBar to collapse and the first one to stay stickied at the top of the screen. I looked at the Materi ...

Guide to streaming audio files using vue.js

I am attempting to incorporate an audio file into my vue.js project using the following code: import sound from '../../recordings/sound.mp4' const audio = new Audio(sound) audio.play() Although this method works perfectly fine, I have encounter ...

Calculate the worth of a specific item within an array of objects and save the outcome as a new attribute

I am attempting to calculate the value in each element and then create a new element called "Count". Rule: Count the quantity if the next element has the same "Quantity" value, then add the total to a new element named "Count". I have tried implementing th ...

What is the process for generating Json using information from a form?

Recently, I embarked on a project that involves creating online tours via a form filled out by the administrator. The data submitted through the form is then mapped into a Mongoose Schema and transformed into JSON. In the createcontent.js file, I utilized ...

Using $.ajax() to store data in the database

Is there a way to save dynamically generated elements from my application.js file into the database? Would the code be similar to this example?: $.ajax({ type: "POST", data: { title: 'oembed.title', thumbnail_url: 'oembed.thumbnail_ur ...

Generate a link that can easily be shared after the content has loaded using

One feature on my website involves a content container that displays different information based on which list item is clicked (such as news, videos, blogs, etc.). This functionality is achieved by using jQuery's load method to bring in html snippets ...

Innovative idea for a time management system based on timelines and scheduling

My latest project involves creating a scrollable scheduler, inspired by vis-timeline and built using Vue.js. One of the main challenges I'm facing is achieving smooth infinite scrolling in all directions (past and future). I must confess that I&apo ...