首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当另一个可观察到的数据发出时,如何将数据推入Observable<any[]>?

当另一个可观察到的数据发出时,如何将数据推入Observable<any[]>?
EN

Stack Overflow用户
提问于 2017-11-08 19:25:30
回答 1查看 2K关注 0票数 0

我想要完成的

当另一个可观测到的发射时,我希望能够将一些数据推入可观测的范围内。第二个可观察性包含可迭代性,因为我需要使用*ngFor (使用异步管道)的模板读取被推送的元素集合。

我的代码

构成部分:

代码语言:javascript
运行
复制
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);
        });
}

模板:

代码语言:javascript
运行
复制
<div *ngFor="let channel of newChannelsIncluded | async" >
    <span>{{channel}}</span>
    <span (click)="removeChannel($event)"</span>
</div>

我被困在特定的地方

题目说什么,如何推到第二个可观察到的可迭代内?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-08 19:49:18

您可能会使用scan

代码语言:javascript
运行
复制
this.newChannelsIncluded = this.eventEmitter.scan((acc, x) => {
  acc.push(x);
  return acc;
}, []);

下面是一个例子:http://jsfiddle.net/zLzzv7j4/

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

代码语言:javascript
运行
复制
this.newChannelsIncluded = new BehaviorSubject<any[]>();
this.eventEmitter.subscribe(newChannel => {
  let channels = this.newChannelsIncluded.value;
  channels.push(newChannel);
  this.newChannelsIncluded.next(channels );
});

此时,由于您使用的是角,我还建议将这个通道列表封装在一个向世界隐藏行为主题的服务中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47188050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档