处理angular2/4 rxjs中多个http可观察对象返回的数据的串联的正确方法是什么? [英] What is the proper way to handle concatenation of data returned from multiple http observables in angular2/4 rxjs?
问题描述
我有5个不同的URL,每个URL返回对象数组中的数据.我想将这些对象合并到一个数组中,该数组存储在本地ANgular2组件中.现在,我在ngOnInit中执行以下操作:
I have 5 different URLs that each return data in the from of an array of objects. I want to concat these objects into a single array that I store local to my ANgular2 componenent. Right now, I do something like this in my ngOnInit:
this.myHttpService.graburl1data()
.subscribe(
response => {
if(!this.mylist) {
this.mylist = []
this.mylist = this.mylist.concat(response);
} else {
this.mylist = this.mylist.concat(response);
}
this.myHttpService.graburl2data()
.subscribe(
response => {
if(!this.mylist) {
this.mylist = []
this.mylist = this.mylist.concat(response);
} else {
this.mylist = this.mylist.concat(response);
}
});
});
必须有更好的方法,请帮忙!
There has to be a better way, please help!
推荐答案
假设您有两个请求,每个请求都返回一个可观察的对象,该对象发出一个数组作为流值:
Suppose you have two requests and each returns an observable that emits an array as a stream value:
const response1 = of([1, 2, 3]);
const response2 = of([4, 5, 6]);
您希望将这些值作为值的流获得-展平.您可以结合使用运算符来做到这一点:
You want to get those values as a stream of values - flattened. You can use a combination of operators to do that:
const merged = merge(response1, response2).mergeMap((a) => {
return a;
});
merged.subscribe((v) => {
console.log(v);
});
您将获得以下输出:
1
2
3
4
5
6
在您的情况下,您将通过调用http
来获得response
观测值:
In your case you will obtains the response
observables by calling the http
:
const response1 = this.myHttpService.graburl1data(),
const response2 = this.myHttpService.graburl2data()
...
因此,最终的代码是:
import { merge } from 'rxjs/observable/merge';
import 'rxjs/add/operator/mergeMap';
const merged = merge(
this.myHttpService.graburl1data(),
this.myHttpService.graburl2data()
).mergeMap((a) => {
return a;
});
merged.subscribe((v) => {
console.log(v);
});
这篇关于处理angular2/4 rxjs中多个http可观察对象返回的数据的串联的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!