Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs combine 2 observables, Angular 2

Tags:

angular

rxjs

I have 2 observables, both http calls:

itemList$:Observable<any[]>;
newItem$:Observable<any[]>;

ngOnInit(){
  itemList$ = this.http.getList(...some url...) // returns array of many items
}

createNewItem(){
  newItem$ = this.http.createNewItem(...some url...) //returns array of one item
}

I would like to call the 'createNewItem()' function from elsewhere and I'd like the result to be merged with the current itemList$ observable results to form one array of items.

In the html I have an async pipe thats listening to itemList$:

<div *ngFor="let item of itemList$ | async">{{item.name}}</div>

How can I merge the newItem$ into itemList$ and have the async pipe display the merged results?

like image 385
Nik Avatar asked Dec 23 '22 21:12

Nik


1 Answers

You can use Observable.merge (I have RxJS version 5.0.1)

Observable.merge(newItem$, itemList$)
          .subscribe(response => {
              // Perform your action
          });

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/merge.md

like image 162
muzurB Avatar answered Dec 28 '22 09:12

muzurB