如何将Observable<News>
添加到可观察数组?
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>
要使用的其他运营商吗?
我尝试了BehaviourSubject
,但它一次只显示一个值。我想显示我附加到arrray的添加项目。
答案 0 :(得分:1)
您可以使用扫描来累积新闻
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>