我有此功能ror将文件转换为显示文件的base64。

 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;
}


而不使用像这样的组件:

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


但是登录到控制台时,this.coverSrc会显示undefined

当我登录此支架时:

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


它显示了base64的值,但当我在localAddress之外登录bracket时,它显示了undefined

DEMO

如何返回函数的值并在其他组件中使用它?

最佳答案

您可以通过Promises或callback进行处理。

-使用回叫

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


-使用承诺

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


您也可以将Observable设为-在此处检查示例-https://jasonwatmore.com/post/2018/06/25/angular-6-communicating-between-components-with-observable-subject

关于javascript - 带 promise 的返回函数值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59444129/

10-10 07:14