有没有办法连接http响应数组,只在角度2的一个数组 [英] Is there any way to concat http response arrays, in just one array in angular 2
问题描述
我有两个数组,Angular 2中的HTTP响应,我需要将另外两个数组转换为test5,但我似乎无法将它们相加,还有其他任何想法吗?
I have this 2 arrays that a HTTP response in Angular 2, I need to convert this two arrays in just another one that is test5, but I seem unable to sum them, any other ideas?
this.test3 = this.http
.get(adresssAPI1)
this.test3= this.http .get("adresssAPI1")
this.test4 = this.http
.get(adressAPI2)
this.test4 = this.http .get("adressAPI2")
this.test5 = this.test 3 + this.test4
this.test5 = this.test 3 + this.test4
推荐答案
使用 Observable.combineLatest
或 Observable.forkJoin
,查看他们的差异< a href =https://stackoverflow.com/questions/41797439/rxjs-observable-combinelatest-vs-observable-forkjoin>这里。
use Observable.combineLatest
or Observable.forkJoin
, see their differences here.
Observable.combineLatest(this.test3, this.test4);
Observable.forkJoin(this.test3, this.test4);
当您订阅 Observable.combineLatest
时,你会得到如下结果:
when you subscribe to Observable.combineLatest
, you will get result like below:
[response3, response4]
您可以使用 Array.reduce
来合并这两个Observables的结果
and you can use Array.reduce
to combine those two Observables' result
// combineLatest
Observable.combineLatest(this.test3, this.test4)
.subscribe(res => {
this.concatResult = res.reduce((pre, next) => {
return [].concat(pre.json().data, next.json().data);
})
});
// forkJoin
Observable.forkJoin(this.test3, this.test4)
.subscribe(res => {
this.concatResult = res.reduce((pre, next) => {
return [].concat(pre.json().data, next.json().data);
})
});
参考此 plunker demo
refer this plunker demo
这篇关于有没有办法连接http响应数组,只在角度2的一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!