0

I have this function ror convert file to base64 for show 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;
}

And use it not components like this:

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

But when log to the console the this.coverSrc it shows me undefined.

When I log in this bracket:

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

It show the value of base64 but when I log the localAddress outside of bracket it shows me undefined.

DEMO

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

1 Answer 1

2

You can handle that either by Promises or callback.

-- Using Call backs

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'];
});

-- Using 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 make of Observable as well - you check the sample here - https://jasonwatmore.com/post/2018/06/25/angular-6-communicating-between-components-with-observable-subject

Sign up to request clarification or add additional context in comments.

1 Comment

can you create a stackblitz demo to reproduce the issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.