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
subscribeis asynchronous so it happens at a later point in time. I will have an answer for you shortly.