1

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?

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.

1 Answer 1

6

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>
Sign up to request clarification or add additional context in comments.

5 Comments

but I want to add news on a button click event, also there is an NewsId that I want to pass it to API based on that news will be fectched.
And if we wanted to add to the top of the array it’s just a normal acc.unshift?
yep you are right.
Thanks. Also are you allowed to put in an if else statement inside scan? Or do we have to use filter? Depending on what button was pressed I either need to do unshift or push
inside scan it is just normal sync code , yes you can

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.