Angular: Async Await- EventListener inside a promise



我在这个问题上挣扎了一天。我想创造这种情况:

<img [src]="userdp | async" />

在component.ts文件中,我只想有这一行:

this.userdp = this._userService.getUserDp();

在getUserDp((中,以下是代码:

async getUserDp() {
return await
this._http.get(APIvars.APIdomain+'/'+APIvars.GET_USER_DP,  { responseType: 'blob' }).toPromise().then( image => {
if(image['type'] === 'application/json') {
return null;
}
const reader = new FileReader();
reader.addEventListener('load', () => {
**return this._dom.bypassSecurityTrustResourceUrl(reader.result.toString());**
});
}, false);
if (image) {
reader.readAsDataURL(image);
}
});
}

Promise不等待读取器在EventListener中加载,任何立即返回语句都会给出预期结果,粗体行是要返回的主要数据。

感谢

您可以通过创建一个返回promise的FileReader方法,在一个地方摆脱回调业务,让您的生活更轻松,也让未来的代码读者的生活更容易。

// return a promise that resolves on the 'load' event of FileReader
async function readAsDataURL(image) {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.addEventListener('load', () => {
resolve(reader.result.toString());
});
// consider adding an error handler that calls reject
reader.readAsDataURL(image);
});
}

既然文件处理代码已经";承诺";,它更容易使用。。。

async getUserDp() {
// temp vars so we can read the code
const url = APIvars.APIdomain+'/'+APIvars.GET_USER_DP;
const options = { responseType: 'blob' };

// await replaces .then() here
const image = await this._http.get(url,  options).toPromise();

// not sure whether this is right, just following OP logic here
// bail if the image (result of the get()) is falsey or is of type json
if (!image || image['type'] === 'application/json') return null;

// simple to call to await file reading
const readerResult = await readAsDataURL(image);
return this._dom.bypassSecurityTrustResourceUrl(readerResult);
}  

替换您对的承诺

reader.onload = function (e) {

}; 

最新更新