我想要完成的
当另一个可观测到的发射时,我希望能够将一些数据推入可观测的范围内。第二个可观察性包含可迭代性,因为我需要使用*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>
我被困在特定的地方
题目说什么,如何推到第二个可观察到的可迭代内?
发布于 2017-11-08 19:49:18
您可能会使用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 );
});
此时,由于您使用的是角,我还建议将这个通道列表封装在一个向世界隐藏行为主题的服务中。
https://stackoverflow.com/questions/47188050
复制相似问题