0

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.test4 = this.http .get("adressAPI2")

this.test5 = this.test 3 + this.test4

Diego
  • 304
  • 4
  • 16

1 Answers1

3

use Observable.combineLatest or Observable.forkJoin, see their differences here.

Observable.combineLatest(this.test3, this.test4);
Observable.forkJoin(this.test3, this.test4);

when you subscribe to Observable.combineLatest, you will get result like below:

[response3, response4]

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);
    })
  });

refer this plunker demo

Pengyy
  • 37,383
  • 15
  • 83
  • 73
  • I think `forkJoin` might be more suitable for http operations. Since `combineLatest` don't wait for observables to complete (leakage maybe?) AFAIK but not really sure if it would make a difference :-) – eko May 25 '17 at 04:39
  • @echonax I'm not familiar with `forJoin`, let me learn it first. :P – Pengyy May 25 '17 at 04:41
  • Check: https://stackoverflow.com/questions/41797439/rxjs-observable-combinelatest-vs-observable-forkjoin – eko May 25 '17 at 04:41
  • 1
    @echonax thanks for the link. :) seems very close for those two operators. – Pengyy May 25 '17 at 04:47
  • @echonax I just run test on combineLatest and seems it'll also wait for all observables to complete. did I miss anything since it's behavior is different from the link you provided(as I understand)? you can check on this https://plnkr.co/edit/7ZaYuZOXuKC5TD4WZkDk?p=preview – Pengyy May 25 '17 at 04:59
  • 1
    That's an awesome test :-) I approach `combineLatest` with caution since it seems to me that it's designed for more continuous stuff like websocket events/streams. Just wanted to point that out :-) – eko May 25 '17 at 05:04
  • @echonax I agree with you about `continuous` :) – Pengyy May 25 '17 at 05:06