首页 > 解决方案 > 将数组从 api 调用传递到第二个 api 调用

问题描述

我正在尝试进行 2 个 api 调用,其中一个 api 获取我需要根据与某个对象一起返回的 ID 进行另一个 api 调用所需的 ID 数组,在这些对象中我可以根据我收到的数据进行操作以显示一些表单输入它。

但是我现在在尝试拨打第二个电话时被卡住了。任何关于如何拨打第二个电话的建议都将不胜感激。

//api.service.ts

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

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

  baseurl = 'http://localhost:5000';

  constructor(private http: HttpClient) { }

  getIds(id){
    return this.http.get(this.baseurl + '/types/' + id);
  }

  getCustomFieldsById(id){
    return this.http.get(this.baseurl + '/types/fields/' + id );
  }
}



//custom.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { ApiService } from '../api.service';
import { map, mergeMap, switchMap } from 'rxjs/operators';


@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html'
})

export class CustomComponent implements OnInit {

  constructor(private apiService: ApiService) {
  }

  ngOnInit(){
  }

  getCustomFields(id){
    this.apiService.getIds(id)
    //this returns an obj in which arrayData constains an array of ids that is needs to be passed into the other api call
    .pipe(
      map((obj: any) => {
        //trying to map the array from the obj
        const data = obj.arrayData;
        return data;
      }),
      mergeMap(data =>
          //data here is an array of ids
          //suppose to receive the ids from the arrayData above 
          this.apiService.getCustomFieldsById(data)
      )
    ).subscribe(response => {
      console.log(response);
    });
  }
}

标签: angular9rxjs6

解决方案


如果您想idids(arrayData) 中获取其中的一系列,您可以使用switchMap代替map

this.apiService.getIds(id)
    .pipe(
      switchMap((obj: any) => {
        const data = obj.arrayData;
        return data;
      }),
      mergeMap(id =>
          this.apiService.getCustomFieldsById(id)
      ),
    ).subscribe(response => {
      console.log(response); // response is a series of CustomField
    });

或者,如果您想获取 的列表customFields,您可以使用forkJoin

this.apiService.getIds(id)
    .pipe(
      map((obj: any) => {
        const data = obj.arrayData;
        return data;
      }),
      mergeMap(ids =>
          forkJoin(ids.map(id => this.apiService.getCustomFieldsById(id)))
      ),
    ).subscribe(response => {
      console.log(response); // response is CustomFields[]
    });

推荐阅读