简体   繁体   English

Angular:异步等待 - promise 内的 EventListener

[英]Angular: Async Await- EventListener inside a promise

I've been struggling since a day on this issue.在这个问题上,我一直在苦苦挣扎。 I want to create this kind of situation:我想创造这种情况:

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

in component.ts file I want to have this line only:在 component.ts 文件中,我只想拥有这一行:

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

in the getUserDp(), here's the code:在 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 is not waiting for the reader to load in EventListener, any immediate return statement gives the intended result, the line in bold is the main data to be returned. Promise 没有等待读者加载到 EventListener 中,任何立即返回语句都会给出预期的结果,粗体行是要返回的主要数据。

Thanks谢谢

You can make your life easier -- and the lives of future readers of the code -- by creating a promise-returning FileReader method, getting out of the callback business in one place.通过创建一个返回承诺的 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);
  });
}

Now that the file handling code has been "promisified", it's easier to use...现在文件处理代码已经“承诺”,它更容易使用......

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

Replace you promise to将您的 promise 替换为

    reader.onload = function (e) {
       
    }; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM