[英]return function value with promise
I have this function ror convert file to base64 for show file.我有这个功能或将文件转换为 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;
}
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
.但是当登录到控制台时
this.coverSrc
它显示我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
.它显示的值
base64
但是当我登录的localAddress
外bracket
它表明我undefined
。
How can I return the value of function and use it in other components?如何返回函数的值并在其他组件中使用它?
You can handle that either by Promises or callback.您可以通过 Promise 或回调来处理。
-- 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您也可以使用 Observable - 您可以在此处查看示例 - https://jasonwatmore.com/post/2018/06/25/angular-6-communicating-between-components-with-observable-subject
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.