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!
Your snippet seems to suggest that there is no dependency between the requests, so you can use
forkJoin
to peform them in parallel:responses
will be an array of the responses in the order in which the request observables were passed toforkJoin
.If you want the requests performed in series, use
concat
andtoArray
instead:Suppose you have two requests and each returns an observable that emits an array as a stream value:
You want to get those values as a stream of values - flattened. You can use a combination of operators to do that:
You will get the following output:
In your case you will obtains the
response
observables by calling thehttp
:So, the final code is: