Angular:Async Await- promise 中的 EventListener

标签 angular typescript promise async-await

一天以来,我一直在为这个问题苦苦挣扎。 我想创造这种情况:

<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 方法,在一个地方摆脱回调业务,您可以让您的生活以及代码的 future 读者的生活更轻松。

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

既然文件处理代码已经被“promisified”,使用起来就更容易了……

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

关于Angular:Async Await- promise 中的 EventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65373154/

相关文章:

javascript - Angular - 将两个 observables 组合在一个 ngIf 中

angular - Ngrx存储了如何在App中正确地清除或重置用户注销后的所有状态

visual-studio - 如何在构建后事件中启动 Typescript 编译

angular - System.import 构建后不搜索文件(Angular2)

javascript - Angular 2+ 从 http 请求返回变量或映射

javascript - 将 (object.function) 作为参数传递

javascript - Q promise 带下划线 .find()

Angular2-csv 如何添加标题?

ios - 模块 '"node_modules/@angular/animations/animations "' has no exported member ' AnimationBuilder'

javascript - 使用 *ngFor 迭代 Promise<any[]>?