Svante
Svante

Reputation: 122

API call with for-loop in Angular

I have an API get call that I want to loop several times depending on the length of the mockInput.json file.

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment';

const localMockInput = 'assets/mock-input.json';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic ' + btoa(environment.api.username+':'+environment.api.password)
  })
};

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) {}

  fetchRealData(_pid: any, _extUserId: any){
    return this.http.get('XXXXX/XXXXX?product='+_pid+'&externalUserId='+_extUserId, httpOptions);
  }

  collectMockRounds(){
   return this.http.get(localMockInput)
  }
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  realData: any = [];
  mockInput: any = [];
  constructor(private api: ApiService) {}

  ngOnInit(){
    this.doArray();
  }

  collectMockInput(){
    this.api.collectMockRounds()
    .subscribe(data => {
      for (const e of (data as any)) {
        this.mockInput.push({
          pId: e.PID,
          extUserId: e.extUserID,
        });
      }
      // console.log('Mock Input Successfully Collected:');
      // console.log(this.mockInput);
    });
  }

  doArray(){
    this.collectMockInput();
    for(let i = 0; i < this.mockInput.length; i++){
      console.log(this.mockInput.length)
      this.api.fetchRealData(this.mockInput[i].pId, this.mockInput[i].extUserId)
      .subscribe(data => {
        for (const d of (data as any)) {
          this.realData.push({
            x: d.x,
            y: d.y,
          });
        }
      },
      error => {
        console.log(error.error.errorMessage);
      });
    }
  }
}

So when I've fetched the mockdata and its length, I want to loop it with my API call. It seems like I'm doing something wrong here; I do not receive any errors or even the console.log within the loop: console.log(this.mockInput.length).

Any advice or hints would be highly appreciated. Thanks in advance

Upvotes: 2

Views: 1141

Answers (1)

AliF50
AliF50

Reputation: 18849

Try something like this:

import { combineLatest } from 'rxjs'
import { switchMap, tap } from 'rxjs/operators'
....
doArray() {
  this.api.collectMockRounds().pipe(
    // this is an array so it should work
    tap(data => console.log(data)), // can you see what the log is here, make sure data is an array...
    // switch to a new observable
    switchMap(data => {
     console.log(data); // make sure this is an array 
     return combineLatest(
      // combine all of the requests
      ...data.map(input => this.api.fetchRealData(input.PID, input.extUserID)),
    })),
  ).subscribe(data => {
      for (const d of (data as any)) {
          this.realData.push({
            x: d.x,
            y: d.y,
          });
        }
}, error => {
   // handle error
 });
}

Upvotes: 1

Related Questions