MergeMap 和 ForkJoin 返回数据



我正在尝试使用mergeMap和forkJoin进行嵌套的http调用。

我想调用一个 API ->再进行两次内部 api 调用。发送第一个 API 和内部 API 的响应。

我有以下代码

testmethod(): Observable<Gen | Observable<[UserForm, OtherForm]>> {
return this.http.get<Gen>("http://test/genData")
.pipe(
map(data => {
const genericData = data;
return genericData;
}),
mergeMap(data => {
const url1 = data.url1;
const url2 = data.url2;
const user = this.http.get<UserForm>(url1);
const other = this.http.get<OtherForm>(url2);
return [data, forkJoin<UserForm, OtherForm>([user, other])];
})
)
}

ts文件

this.service.testmethod().subscribe(item => {
console.log('test(): ', item);
}

输出:

test(): {...}
test(): Observable

两个 test(( 正在记录到控制台。我想通过订阅方法获取数据。

我的做法是否正确。从服务返回时我需要更改什么吗?

mergeMap中,您应该始终返回一个可观察量,这里您返回一个数组。

您可以将返回语句修改为:

return forkJoin<Gen, UserForm, OtherForm>([of(data), user, other]);

最新更新