deliver a promise with a function's value

I have created a function to convert a file to base64 for displaying the file.

 ConvertFileToAddress(event): string {

    let localAddress: any;
    const reader = new FileReader();
    reader.readAsDataURL(event.target['files'][0]);
    reader.onload = (e) => {
        localAddress = e.target['result'];
    };
    return localAddress;
}

I am trying to use this function in other components like this:

this.coverSrc=this.localization.ConvertFileToAddress(event);

However, when I log this.coverSrc to the console, it shows me undefined.

When I log within this bracket:

    reader.onload = (e) => {
        localAddress = e.target['result'];
    };

It displays the value of base64. But when I log localAddress outside of the bracket, it shows me undefined.

DEMO

How can I properly return the value from the function and use it in other components?

Answer №1

To solve this issue, you have the option of using either Promises or callbacks.

-- Implementing Callbacks

ConvertFileToAddress(event, callback): string {
    const reader = new FileReader();
    reader.readAsDataURL(event.target['files'][0]);
    reader.onload = callback;
}

this.localization.ConvertFileToAddress(event, (e) => {
     this.coverSrc = e.target['result'];
});

-- Utilizing Promises

ConvertFileToAddress(event): string {

    return new Promise((resolve, reject) {

        const reader = new FileReader();
        reader.readAsDataURL(event.target['files'][0]);
        reader.onload = (e) => {
             resolve(e.target['result']);
        };
    });
}

this.localization.ConvertFileToAddress(event).then((data) => {

   this.coverSrc = data;
});

You can also explore using Observables - check out a sample 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

Troubleshooting Cross-Origin Resource Sharing (CORS) issues with Font Awesome font in

For a while now, I've been using Angular and Material without any issues. However, recently I encountered a problem that has me puzzled. When running my Angular app from IntelliJ, an error message appeared in the console. The error stated: Access to ...

Display the initial MUI components from an array of data in a distinctive manner

Trying to display the content of an Accordion by passing props down through a list array to a component. I have identified the issue but unsure how to call the component and pass the props differently. Below is the code snippet. Code for the parent compon ...

Choose a navigation item from the list containing a nested span element

I've implemented selectnav from GitHub and it's functioning perfectly. However, my menu consists of list items with a description span inside each one, resulting in menu items structured as shown below: <li><a href="somelink.html">Ch ...

Angular is unable to detect the dynamically loaded page when using Extjs

Within my Extjs SPA system, I have integrated Angular along with the necessary modules to be used on a page that is being referred in an external HTML panel in Extjs. While Angular is defined and functioning properly everywhere else, it seems to not work ...

update the element that acts as the divider in a web address (Angular)

Is it possible to modify the separator character used when obtaining the URL parameters with route.queryParams.subscribe? Currently, Object.keys(params) separates the parameters using "&" as the separator. Is there a way to change this to use a differe ...

Is it advisable to include auto-generated files in an npm package upon publication?

I have a TypeScript NPM package where my build process compiles all *.ts files into myLib.d.ts, myLib.js, and myLib.js.map. In order for my NPM package to function properly, it requires the src/*.ts files as well as the auto-generated myLib.* files. Howe ...

Struggling to transfer information between different components?

I recently implemented a delete button functionality in my project to remove elements when clicked, but I'm facing an issue where the input decorator is not properly receiving data for deletion. When I console log, it shows that the array is empty whi ...

Encountered an issue while resolving dependency tree for angular tslib

When running npm install, I encountered the error shown in this image: https://i.stack.imgur.com/PInQE.png The CLI version is Angular CLI: 9.1.8. Any assistance would be greatly appreciated. Thank you! ...

Choosing bookmarkable views in Angular 5 without using routes

I'm currently working on a unique Angular 5 application that deviates from the standard use of routes. Instead, we have our own custom menu structure for selecting views. However, we still want to be able to provide bookmarkable URLs that open specifi ...

How can multiple buttons be added to each row in Jquery datatables and how can events be applied to them?

I currently have one button, but I am in need of two buttons. These buttons will trigger MySql commands when clicked to retrieve data from the database. How can I set up an event handler for these buttons? $(document).ready(function () { var table= ...

Tips on employing the sendkeys function in selenium webdriverjs through promise chaining

Here is the coding snippet: driver.get(url).then(function(){ txtFnn = driver.findElement(webdriver.By.xpath(xpath)); return txtFnn; }).then(function(){ txtFnn.sendkeys("12345678"); }) Issue: An error occurred: Typ ...

Retrieving a boolean value (from a JSON file) to display as a checkbox using a script

Currently, I am utilizing a script to fetch data from a Google Sheet $.getJSON("https://spreadsheets.google.com/feeds/list/1nPL4wFITrwgz2_alxLnO9VBhJQ7QHuif9nFXurgdSUk/1/public/values?alt=json", function(data) { var sheetData = data.feed.entry; va ...

Struggling to make type definitions work in react-hook-form 7

Upon defining the types of my form fields, I encountered an issue where each field seems to take on all three different types. This is puzzling as I have specified 3 distinct types for my 3 different fields. What could be causing this confusion? https://i ...

Repeating every 3 to 6 months on later.js commencing from a specified date

Currently, I am working on setting up recurring events every 3 and 6 months using the later.js library which can be found at https://github.com/bunkat/later. The code implementation looks like this: // Assuming my value.scheduled_date is set to 2018-09-0 ...

Sharing Angular classes and components between a shell and Micro Frontends using module federation

Currently, I am experimenting with a module federation proof of concept in Angular, taking inspiration from Manfred's example. My goal is to figure out a way to share utility classes, directives, individual components, and any other code that does not ...

Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views: var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.myConsta ...

The data type 'Observable<{}[]>' cannot be matched with the type 'AngularFireList<any>'

I have been learning how to use AngularFire2 by following this tutorial. Encountered the error: 'Type 'Observable<{}[]>' is not assignable to type 'AngularFireList'. Property 'query' is missing in type 'Obse ...

Subscribing with multiple parameters in RxJS

I am facing a dilemma with two observables that I need to combine and use in subscribe, where I want the flexibility to either use both arguments or only one. I have experimented with .ForkJoin, .merge, .concat but haven't been able to achieve the des ...

The test failed to execute due to disconnection (0 occurrences) as no message was received within the 30000 ms timeframe

Currently, I am facing an issue with my Angular application. When I execute the "ng test" command, it displays an error message stating 'Disconnected (0 times), because no message in 30000 ms.' I have tried updating both karma and jasmine package ...

Route.get() is expecting a callback function, however it received an object of undefined instead

In my nodejs application using typescript, I am working on separating the routing by introducing interfaces and controllers to handle the logic. app.ts const countryRoutes = require('./routes/countryroute') app.use('/countries', count ...