解析一组可观测值(以角度表示)



对于我的应用程序,我有一个Angular组件。这个组件有一组id。对于每个id,我希望它进行一个API调用(Observable(,当所有API调用完成时,我希望运行一个函数。所以我的组件看起来是这样的:

export class UploadFormFieldComponent implements OnInit {
constructor(private readonly apiService: ApiService) {}
@Input()
documentIds: string[];
ngOnInit(): void {
this.downloadFiles();
}
downloadFiles() {
// iterate over documentIds and download file for each id
}
private downloadFile(id: string): Observable<{ id: string; name: string }> {
return this.apiService.getFile(id);
}
finalFunction() {
console.log('This function should run after each file is uploaded');
}
}

downloadFile功能运行良好。然而,我无法在每个downloadFile函数都超过极限后运行finalFunction。如何塑造我的下载文件功能?

您可以将id数组映射到一个可观察对象数组,每个可观察对象都通过id下载特定项目,然后使用forkJoin创建一个单独的可观察对象:

downloadFiles(): Observable<{ id: string; name: string }[]> {
const downloads = this.documentIds.map(id => this.downloadFile(id));
return forkJoin(downloads);
}

最新更新