每当另一个observable发出时,如何将数据推送到Observable <any []>?

时间:2017-11-08 19:25:30

标签: angular rxjs reactive-programming

我打算完成什么

我希望能够在另一个observable发出时将一些数据推送到一个observable中。第二个observable包含一个iterable,因为我需要一个带有* ngFor的模板读取的推送元素集合(使用异步管道)。

我的代码

组件:

eventEmitter: Observable<any>;
newChannelsIncluded: Observable<any[]>;

ngOnInit() {
    // create an observable that contains an iterable
    this.newChannelsIncluded = Observable.from([]);

    // create an emitter to grab the data I will push to the iterable
    this.eventEmitter = Observable.fromEvent(
        document.querySelectorAll('ul.dropdown'), 'click');

    // push the data into the iterable inside the observable
    this.eventEmitter
        .subscribe( e => {             
            this.newChannelsIncluded
                .pushIntoTheIterableInsideTheObservable(e.target.value);
        });
}

模板:

<div *ngFor="let channel of newChannelsIncluded | async" >
    <span>{{channel}}</span>
    <span (click)="removeChannel($event)"</span>
</div>

我遇到的具体地点

问题标题是什么,如何在第二个observable中推送到iterable?

1 个答案:

答案 0 :(得分:1)

您可以使用scan

this.newChannelsIncluded = this.eventEmitter.scan((acc, x) => {
  acc.push(x);
  return acc;
}, []);

以下是一个示例:http://jsfiddle.net/zLzzv7j4/

但是,如果您还想在以后删除这些项目,则应在行为主题中维护此频道列表。

this.newChannelsIncluded = new BehaviorSubject<any[]>();
this.eventEmitter.subscribe(newChannel => {
  let channels = this.newChannelsIncluded.value;
  channels.push(newChannel);
  this.newChannelsIncluded.next(channels );
});

此时,由于您使用的是Angular,我还建议将此频道列表封装在一个隐藏行为主体的服务中。