Karlito
Karlito

Reputation: 83

Angular2 merge part of objects

I need to merge two same type observables and return same type observable in Angular2 function.
So all I want to do is:

from this:

obs1.subscribe(obs => console.log(obs))
(where I get): 
{
   count: 10,
   array: <someObservable[]> 
}

and

obs2.subscribe(obs => console.log(obs))
(where I get): 
{
   count: 10,
   array: <someObservable[]> (different objects)
}

into:

{
   count: 10 (count always the same number),
   array: <someObservable[]> (combined array from obs1 and obs2)
}

What is the simplest way to achieve that? (Maybe it is simple to even junior level angular developer, but I have to it quickly and Im newbie in this sphere). Thanks in advice.

---UPDATE---

from this code part :

const obs2 = obs1.pipe(
        switchMap(value => {
          return this._loadMoreTextSearchSub.asObservable()
          .pipe(pairwise(),
          map(params => this.getPagingParameters(params[0], params[1])),
          switchMap(request),
          map(response => response.packages),
          scan<SearchPackage[]>((all, current) => {
            return [...all, ...current];
          }, 
          value.packages
          ));
        }))
        .subscribe(data => console.log('sec', data));

I get array of objects. How could I wrap that array into the object and set extra property - 'count'?

Current:
[{...}, {...}, {...}, {...}]
Desired:
{count: some_number, array: [{...}, {...}, {...}]}

Upvotes: 1

Views: 66

Answers (1)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

If you need to call the Observables subsequently then you can use mergeMap() for the same.

Lets say, you call obs1 first, once you have the result of obs1, you call obs2, then combine both the results and return.

obs1.pipe(mergeMap((firstResult) => {
    return obs2.pipe(map((secondResult) => {
        return { count: firstResult.count, array: [...firstResult.array, ...secondResult.array] };
    }))

})).subscribe((data) => {
    console.log(data);
})

Upvotes: 2

Related Questions