2

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

1
  • The subscribe is asynchronous so it happens at a later point in time. I will have an answer for you shortly. Commented Mar 5, 2020 at 14:38

1 Answer 1

1

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
 });
}
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you for your swift reply! I tried the following code example above but it seems like I've issues with .map. I receive the following error: Property 'map' does not exist on type 'Object'. "typescript": "~3.5.3" "rxjs": "~6.4.0", Angular 8 I tried to install rxjs-compat but to no avail. Thanks in advance.
I think it's the array map on ...data.map where data is an object and not an array. I added a tap to see the log, can you tell me what it logs? Is it an array or object? And if it is an object, can you show me the object?
Hi AliF50, thank you for your dedication to help me with this; the tap gave me back the entire mock-input.json array; which contains 3 objects: i.imgur.com/pEsVHx7.png. Cheers
So it is an array? And you're unblocked/figured it out?
It is indeed an array; however, I've not figured out yet fully; I receive: x: undefined in the log output and I still receive: ERROR in src/app/app.component.ts(116,17): error TS2339: Property 'map' does not exist on type 'Object'. in the CLI.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.