简体   繁体   English

Rxjs结合了2个Observable,Angular 2

[英]Rxjs combine 2 observables, Angular 2

I have 2 observables, both http calls: 我有2个observable,两个http调用:

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. 我想从其他地方调用'createNewItem()'函数,我希望将结果与当前的itemList $ observable结果合并,形成一个项目数组。

In the html I have an async pipe thats listening to itemList$: 在html中我有一个监听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? 如何将newItem $合并到itemList $并让异步管道显示合并结果?

You can use Observable.merge (I have RxJS version 5.0.1) 您可以使用Observable.merge (我有RxJS版本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 https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/merge.md

You could use a Subject instead of Observable s. 您可以使用Subject而不是Observable 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM