Reputation: 7192
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?
Upvotes: 4
Views: 8885
Reputation: 317
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
Upvotes: 9
Reputation: 6468
You could use a Subject
instead of Observable
s. As soon as you create a new item, hand it over to the Subject and emit it.
itemList$:AsyncSubjct<any>;
createNewItem(){
this.http.createNewItem(...some url...).subscribe(data => {
this.itemList$.next(data);
}
Upvotes: 1