angular - 是否可以返回发出通过等待异步方法构造的数组的 Observable?
问题描述
我有下面的方法可以构建但不起作用:
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;
}
那么这样的事情可能吗?
解决方案
您可以尝试使用“fromPromise”方法将 promise 对象(由 async 方法返回)转换为 observable。此外,使用“forkJoin”将所有可观察输出连接到单个可观察结果中,最后,将“map”替换为“switchMap”,将流替换为可观察累积结果。以下是可以帮助您的代表性代码:
function getCount(): Observable<number> {
return of(10);
}
// This is your "getAsync" method
async function getNumberPromise(value: number) {
return value;
}
// This is your inner 'newState.fileResults.forEach' loop
function getNumberObservables(entries: number[]): Observable<number[]> {
return forkJoin(entries.map((value, index) => {
return from(getNumberPromise(index));
}));
}
// this is your 'this.ngRedux.select<ICommunicationState>('communication').pipe(map(...'
function getAllFiles(): Observable<number[]> {
return getCount().pipe(switchMap(count => {
const entries = new Array(count);
return getNumberObservables(entries);
}));
}
推荐阅读
- c - 如何旋转矩阵?C
- javascript - 使用 npm install --production 创建生产版本时抛出错误
- r - 如何在未知行位置导入具有错误标题和正确标题的文件
- c# - 如何使用 IEnumerator(Unity, C#) 解决错误?
- ios - 在没有 StoryBoard 的情况下点击通知时访问特定的 ViewController(以编程方式)
- python - 区分两个数组的Pythonic方式
- kotlin-coroutines - 在协程中完成后台工作后更新 UI
- javascript - 反应测试笑话“不变违规:元素类型无效:预期字符串......”
- java - Recyclerview findViewHolderForAdapterPosition() 返回 null
- flutter - 如何为 Flutter 应用添加首次启动视觉帮助?