How to push to Observable of Array in Angular 4? RxJS

Viewed 28648

I have a property on my service class as so:

articles: Observable<Article[]>;

It is populated by a getArticles() function using the standard http.get().map() solution.

How can I manually push a new article in to this array; One that is not yet persisted and so not part of the http get?

My scenario is, you create a new Article, and before it is saved I would like the Article[] array to have this new one pushed to it so it shows up in my list of articles.

Further more, This service is shared between 2 components, If component A consumes the service using ng OnInit() and binds the result to a repeating section *ngFor, will updating the service array from component B simultaneously update the results in components A's ngFor section? Or must I update the view manually?

Many Thanks, Simon

3 Answers

As you said in comments, I'd use a Subject.

The advantage of keeping articles observable rather than storing as an array is that http takes time, so you can subscribe and wait for results. Plus both components get any updates.

// Mock http
const http = {
  get: (url) => Rx.Observable.of(['article1', 'article2']) 
}

const articles = new Rx.Subject();

const fetch = () => {
  return http.get('myUrl').map(x => x).do(data => articles.next(data))
}

const add = (article) => {
  articles.take(1).subscribe(current => {
    current.push(article);
    articles.next(current);
  })
}

// Subscribe to 
articles.subscribe(console.log)

// Action
fetch().subscribe(
  add('article3')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script>

Instead of storing the whole observable, you probably want to just store the article array, like

articles: Article[]

fetch() {
    this.get(url).map(...).subscribe(articles => this.articles)
}

Then you can manipulate the articles list using standard array manipulation methods.

If you store the observable, it will re-run the http call every time you subscribe to it (or render it using | async) which is definitely not what you want.

But for the sake of completeness: if you do have an Observable of an array you want to add items to, you could use the map operator on it to add a specified item to it, e.g.

observable.map(previousArray => previousArray.concat(itemtToBeAdded))

ex from angular 4 book ng-book

Subject<Array<String>> example =  new Subject<Array<String>>();


push(newvalue:String):void
{
  example.next((currentarray:String[]) : String[] => {
    return  currentarray.concat(newValue);
   })

}

what the following says in example.next is take the current array value Stored in the observable and concat a new value onto it and emit the new array value to subscribers. It is a lambda expression.I think this only works with subject observables because they hold unto the last value stored in their method subject.getValue();

Related