在Angular中使用for循环进行API调用

时间:2020-03-05 14:19:48

标签: angular api for-loop

我有一个API get调用,我想循环几次,具体取决于模拟输入.json文件的长度。

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

因此,当我获取了模拟数据及其长度时,我想用我的API调用循环它。看来我在这里做错了;我没有收到任何错误,甚至没有收到循环中的console.log:console.log(this.mockInput.length)

任何建议或提示将不胜感激。 预先感谢

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

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