TopBanana9000
TopBanana9000

Reputation: 898

How to combine two observable arrays of the same type in angular 6?

I cannot seem to figure out how to combine two observable arrays. This is using Angular 6, rxjs 6.3.2

Example code:

var arrayOfUsers = this.httpCallToGetObservableArrayOfUsers();
var anotherArrayOfUsers = this.httpCallToGetADifferentArrayOfUsers();

//how do I combine these two Observable<User[]>?

Thanks in advance

Upvotes: 2

Views: 4600

Answers (1)

Quentin Fonck
Quentin Fonck

Reputation: 1315

Since your observables are http calls, I assume they complete after emitting. you can use forkJoin to combine them:

var arrayOfUsers = this.httpCallToGetObservableArrayOfUsers();
var anotherArrayOfUsers = this.httpCallToGetADifferentArrayOfUsers();

const allUsersArray = forkJoin(arrayOfUsers, anotherArrayOfUsers).pipe(
    map(([users, otherUsers]) => users.concat(otherUsers))
);

if your observables do not complete, use combineLatest:

const allUsersArray = combineLatest(arrayOfUsers, anotherArrayOfUsers).pipe(
    map(([users, otherUsers]) => users.concat(otherUsers))
);

Upvotes: 7

Related Questions