是否有可能返回Observable,该Observable发出通过等待异步方法构造的数组?

问题描述 投票:1回答:1

我下面有可以构建但无法正常工作的方法:

  get screenShotResults$(): Observable<ScreenshotFile[]> { 
    return this.ngRedux.select<ICommunicationState>('communication').pipe(map(newState => {
      const ret: ScreenshotFile[] = [];
      newState.fileResults.forEach(async result => {
        if (result.type === 'SCREENSHOT') {
          const blob = await this.fileLocalStoreService.getAsync(result.id);
          if (blob !== undefined) {
            ret.push({id: result.id, blob: blob})
          }
        }
      });
      return ret;
    }));
  }

想法是它从indexedDb获取文件。但是由于没有同步的API,因此我在实现过程中苦苦挣扎。

等待的方法看起来像这样:

  public async getAsync(key: string) {
    let blob: IFileBlob | undefined;
    blob = await this.db.files.get(key);
    if (blob === undefined) {
      return undefined
    }
    return blob.file;
  }

它正在使用Dexie。

interface IFileBlob {
  id: string;
  file: Blob;
}

newState.fileResults是这些的数组:

export interface IFileResult {
  id: string;
  type: string;
}

那么有可能这样吗?

angular async-await rxjs angular2-observables
1个回答
0
投票

您可以尝试使用“ fromPromise”方法将promise对象(由异步方法返回)转换为可观察的对象。另外,使用“ forkJoin”将所有可观察到的输出连接成单个可观察者,最后,将“ map”替换为“ switchMap”,以将流替换为可观察的累积结果。以下是可以帮助您的代表性代码:

© www.soinside.com 2019 - 2024. All rights reserved.