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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

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 :-)
@echonax I'm not familiar with forJoin, let me learn it first. :P
@echonax thanks for the link. :) seems very close for those two operators.
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 :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.