RxJS将可观察到的内容追加到打字稿中的可观察到的数组列表中 [英] RxJS append observable to observable array list in typescript

查看:79
本文介绍了RxJS将可观察到的内容追加到打字稿中的可观察到的数组列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Observable<News>添加到可观察数组?

How to add Observable<News> to an array of observable ?

newsArray: Observable<Array<any>>;

addNews(newsId: number) {
   let news = this.newsService.getNewNews(newsId); // this returns a Observable<News> type.

  //I want to add `news` to `newsArray` to display it in UI.
}

HTML:

<li *ngFor="let item of (newsArray | async)">
  <div>{{item.Id}}: {{item.DataValue}}</div>
</li>

还有其他运算符要使用吗?

Any other operators to use?

我尝试了BehaviourSubject,但是一次只显示一个值.我要显示要添加到错误中的添加项目.

I tried BehaviourSubject but it displays only one value at a time. I want to display add items that I am appending to an arrray.

推荐答案

您可以使用扫描来积累新闻

You can use scan to accumulate news

news$:Observable<any>
loadMore$=new Subject<number>()

ngOnInit(){
 this.news$=this.loadMore$
 .switchMap((newsId)=>this.newsService.getNewNews(newsId))
 .scan((acc,curr)=>{
    acc.push(curr)
    return acc
 },[]).startWith(null)
}

addNews(newsId: number) {
  this.loadMore$.next(newsId);
}

HTML

<li *ngFor="let item of (news$ | async)">
  <div>{{item.Id}}: {{item.DataValue}}</div>
</li>

这篇关于RxJS将可观察到的内容追加到打字稿中的可观察到的数组列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆