angular9 - 将数组从 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);
});
}
}
解决方案
如果您想id
在ids
(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[]
});
推荐阅读
- java - 在大文本文件中查找文本数据的快速方法是什么?
- google-sheets - 当我尝试 STDEV、STDEVA、STDEVP、STDEVPA 时,表格对我的数据集做了奇怪的事情
- android - 使用 pydub+ffmpeg 编码的 M4a (mp4) 音频文件无法在 Android 上播放
- python - 如何使用 Python 2.7 在 anaconda 提示符中安装 zip(或 tag.gz)文件(我想安装 PyQt4 的版本)
- kotlin - Spring WebFlux,提取请求体
- google-apps-script - 如何使用 Google Apps 脚本检查 Google 表格中的 URL 重定向
- java - 测试中未提供 Hilt 依赖项
- postgresql - 如何将 SUM 添加到 typeorm 中的嵌套查询?
- wifi - 如何解决 Nodemcu ESP8266 的 Exception3 问题?
- flutter - 用列表填充多选
或列表