带有RxJS的多个HTTP请求,带有参数
我称之为api
https://jokerleb.com/wp-json/wp/v2/ads/
我抓住每个广告的 id
,然后将其附加到此网址
I grab the id
of each ad and then I append it to this url
https://jokerleb.com/wp-json/wp/v2/media?parent=24385
我的代码是
loadAds() {
let i = 0;
this.HttpClient.get(ENV.site_url + ENV.ads_url)
.subscribe(res => {
this.ads = this.ads.concat(res);
this.HttpClient.get(ENV.site_url + ENV.ads_thumb_url + this.ads[i].id + "&&ads/" + this.ads[i].id)
.subscribe(res => {
this.items = this.items.concat(res);
console.log(ENV.site_url + ENV.ads_thumb_url + this.ads[i].id + "&&ads/" + this.ads[i].id);
i++;
})
}
)
}
代码有效但是:
- 我最终得到了两个不同的数组,我无法将它们正确地合并到一个数组
items
- 我讨厌事实上,我必须做两个单独的订阅,它工作但感觉不对
基本上我想最终得到一个包含所有数组的数组来自两个端点的项目。
Basically I want to end up with an array containing all the items from both endpoints.
所以对象 id = 2438 5
应该返回一个数组
So object id=24385
should return an array of
https://jokerleb.com/wp-json/wp/v2/ ads / 24385
和
https:/ /jokerleb.com/wp-json/wp/v2/media?parent=24385
您需要做的是使用 concatMap
合并两个列表。
例如:
What you need to do is merge the two lists using concatMap
.
For example:
getService1(id1).pipe(
// take array1 and return [array1, array2]
concatMap( array1=> return zip(of(array1), getService2(array1[information])))
// concat Array1 and array2
map( [array1, array2] => array1.concat(array2))
)
.subscribe( combinedArray => ...)
如果您的服务每个发出1个项目,您可以用 switchMap
替换 concatMap
, mergeMap
,或 exhaustMap
;在这种情况下,它们都表现相同。此外,您还可以使用 forkJoin
替换 zip
。相反,如果您的服务发出的值超过1,则必须根据需要选择行为。
If your services emit 1 item each, you can replace concatMap
with switchMap
, mergeMap
, or exhaustMap
; they all behave same in this context. Additionally, you can also substitute zip
with forkJoin
. On the contrary, if your services emit more than 1 value, you will have to choose the one that behaves according to your needs.