KevinTale
KevinTale

Reputation: 1858

Subscribe to an observable within a loop in Angular

I'm having a use case where I need to subscribe to an Observable then looping the response in order to subscribe to another Observable using a data from the first Observable.

  getTasks(taskType: Observable<any>): void {
    taskType // Subscribing to the first Observable
      .subscribe(
        (tasks: any) => {
          let row: InboxTasks;
          for (const task of tasks) { // Looping through the result
            if (task.assigned_id) { // I need to extract that data in order to use it as an argument of the second Observable below
              this.auth.getUserById(task.assigned_id).subscribe((user) => this.username = `${user.firstname} ${user.lastname}`);
            }
            row = {
              assigned: this.username ? this.username : '', // Here I use my newly created property
              task: task.displayName
            };
            this.rowData = [
              ...this.rowData,
              row
            ];
          }
        }
      );
  }

Using that method the loop while be executed before the second Observable can be complete. How can I manage to use this second Observable in that scenario?

Thanks

Upvotes: 2

Views: 3499

Answers (1)

martin
martin

Reputation: 96889

You can first gather all inner Observables based on the response from the first Observable and wait until all of them complete with forkJoin:

taskType
  .pipe(
    concatMap(tasks => {
      const observables = [];
      for (const task of tasks) {
        observables.push(this.auth.getUserById(task.assigned_id));
      }
      return forkJoin(...observables).pipe(
        map(innerResults => ({
          innerResults,
          tasks
        }))
      );
    })
  )
  .subscribe(({ innerResults, tasks }) => ...);

Upvotes: 5

Related Questions