Search code examples
angularrxjsobservable

Resolving a set of Observables (in Angular)


For my application I have an Angular component. This component has a set of id's. For each id I want it to make an API Call (Observable) and when all API calls are finished, I want to run a function. So my component looks like this:

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

The downloadFile function works fine. However I can't get the finalFunction to run after each downloadFile function has been excecuted. How to I shape my downloadFiles function?


Solution

  • You could map the array of ids to an array of observables that each download the specific item by id, then use forkJoin to create a single observable:

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