Creating a variable that is not defined and then converting it into

I have an issue with a function that returns an Observable. The problem is that when the function is called, the parameter works fine, but its value becomes undefined within the Observable.

This is the function in question:

import {Observable} from 'rxjs/Observable';

export function ToBase64(inputFile) {
    console.log('Input:', inputFile); //The variable has the correct value here
    let observable = new Observable(observer => {
        try {
            console.log('Input in observable:', inputFile); //here it is undefined :(
            var image = {};

            var reader = new FileReader();

            reader.onload = (e) => {
                image.base64 = btoa(e.target.result);

                var stringBase64 = `data:${image.filetype};base64,${image.base64}`;

                observer.next(stringBase64);
                observer.complete()
            };

            console.log(inputFile);
            var inputFile = inputFile.files[0];
            image.filetype = inputFile.type;
            image.size = inputFile.size;
            image.filename = inputFile.name;
            reader.readAsBinaryString(inputFile);
        } catch (e) {
            observer.error(e);
        }
    });

    return observable;
}

This function is being used in an Angular2 App like this:

//imports...

export class MedicosListComponent {
    @ViewChild('imagenMedico') imagenMedico:any;
    private image:string;

    constructor() {

    }

    showAllWeas() {
        ToBase64(this.imagenMedico.nativeElement).subscribe(
            data => {
                alert(data)
            },
            error => alert(error)
        )
    }
}

The medicoList variable is of type file input.

Thank you in advance for any assistance.

Answer №1

The issue seems to be related to the scope of the code. Simply adding an extra variable inside the function seems to resolve the problem. Here's the modified code:

import {Observable} from 'rxjs/Observable';

export function ToBase64(inputFile) {
    var i = inputFile; // <------- extra variable
    return new Observable(obs => {
        try {
            var image = {};
            var reader = new FileReader();

            reader.onload = (e) => {
                image.base64 = btoa(e.target.result);

                var stringBase64 = `data:${image.filetype};base64,${image.base64}`;

                obs.next(stringBase64);
                obs.complete()
            };

            var inputFile = i.files[0]; //here i has the correct value
            image.filetype = inputFile.type;
            image.size = inputFile.size;
            image.filename = inputFile.name;
            reader.readAsBinaryString(inputFile);
        } catch (e) {
            obs.error(e);
        }
    });
}

That should do it!

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

Running "ng lint --fix" does not automatically correct the issues in my files, but it does effectively pinpoint all the errors that need to be addressed

I am currently working on resolving lint issues present in files that are automatically generated through openapi-generator. Let's take a look at one of the files that needs fixing: To address these errors, I have been using the following command: ...

There seems to be an issue with transitioning the React.js page

I'm currently working on managing the page with react-hook, react-router-dom, and redux. The login functionality has been implemented, and I've written the code to redirect to the main page upon successful login. To achieve this, I utilized hi ...

Issue verifying the initial certificate in Nodeshift

Currently, I am in the process of deploying an Angular application using nodeshift, but I have encountered the error message "unable to verify the first certificate" whenever I execute the following command: nodeshift --strictSSL=false --dockerImage=buch ...

What is the best way to reduce the size of a Base64/Binary image in Angular6

I utilized the Ngx-Webcam tool to capture images from my camera. My goal is to obtain both high quality and low quality images from the camera. Although this library provides me with Base64 images, it offers an option to reduce the size using imageQuality ...

Sophisticated method for retrograding every Angular component for AngularJS

I am in the process of transitioning my app from angularjs to angular. As I create new angular components, I am looking for a more streamlined way to import and downgrade them automatically. Is there an elegant solution for this? Here is my current code: ...

Is it possible for a voiceover artist to initiate API requests?

As I work on the registration feature of my application, I am faced with the requirement that email addresses must be unique in the database. Since I am responsible for the front-end development, I am considering creating a Value Object (VO) that can make ...

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

Typescript types for the Google Calendar API

Is there anyone out there who can confirm whether the google Calendar API (via the npm package googleapis) for node.js or browser supports types that can be utilized in TypeScript? This would allow for a more strongly typed approach in projects using node ...

Stop SVG Image Caching in Angular

I encountered an issue while attempting to dynamically load an image in Angular without caching. The error I saw in the console was: ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous v ...

Managing the re-rendering in React

I am encountering a situation similar to the one found in the sandbox example. https://codesandbox.io/s/react-typescript-fs0em My goal is to have Table.tsx act as the base component, with the App component serving as a wrapper. The JSX is being returned ...

Bringing in a directive to a component in Angular

Can the Directive be imported into a Component without adding it to ngModule.declarations? I came across the CustomDirective for Telerik Angular Grid, which recommends using custom directives in the grid. However, I only need this directive in one compone ...

Visual Studio 2017, ASP.NET framework, Typescript programming language, and node package manager

My ASP.net application in Visual Studio used to only utilize JavaScript, but now I am looking to incorporate Typescript. While the installation and transpiling process went smoothly, I encountered an issue when attempting to import modules. I decided to u ...

Tips for configuring the navigation links on the current page using Bootstrap

In my Angular application, I have set up navigation links for home, about, notifications, and logout. However, when I click on the home link, it redirects me to the login page instead of remaining on the current page. I need the functionality to stay on ...

Develop a fresh class by inheriting from HTMLDivElement and expanding its prototype

My goal is to add a new method to the HTMLDivElement prototype without cluttering the HTMLDivElement itself with my custom methods. This has led me to attempt creating a new class that extends the HTMLDivElement. export class ScrollableElement extends HTML ...

Side navigation in Angular is not causing the main content to shrink

In my layout, I have a container that includes two sidenavs and multiple tables in between them. When I toggle the left sidenav, instead of the expected behavior where the content shrinks to accommodate the sidenav, the tables get pushed to the right as if ...

Issue with displaying hamburger menu items when using data-toggle in Angular

I've been diving into learning Angular and Bootstrap lately. I wanted to merge some existing HTML content into an Angular component, but ran into issues with its functionality. When I attempt to toggle the hamburger menu icon, nothing happens, and the ...

Sort columns in a MUI datatable

I am facing an issue with sorting in a column that represents an object. Although I can display the desired value, the sorting functionality does not seem to work for that particular column. Here is an example to provide better clarity: const [data, set ...

Unable to retrieve component name using React.Children

While working with react in the nextjs framework, I attempted to create my own dropdown component structured as follows: <Dropdown> <DropdownToggle>Action</DropdownToggle> <DropdownMenu> <DropdownItem>Menu 1</Dr ...

In React, the issue arises when a Typescript declaration merging cause is referenced as a value but is being mistakenly used as a type

I am trying to come up with a solution to avoid the hassle of brainstorming names that seamlessly incorporate suffixes or prefixes in order to differentiate between declarations and component names. After being inspired by this resource Avoid duplicate id ...

Monitoring changes in the value of dynamically added form elements within dynamically added grid rows using Angular

When I activate edit mode in my grid, each row becomes editable with various fields like dropdowns and input fields. My requirement is that when the dropdown value changes to a specific value, only then the input field should be enabled for editing; otherw ...