pezetter pezetter -4 years ago 393
TypeScript Question

Angular 2 - rxjs - Observable array

In my template I subscribe to an observable array like so:

<div *ngFor="let item of activities | async">...</div>

I changed my activities array to an observable array because I like the idea of the view subscribing and unsubscribing from my observables.

My question is, after initially retrieving the observables and mapping them into an activities object array, how do I append or prepend activities to that array without overwriting the entire observable array?

To be specific, I am creating an infinite scroll and upon the new http request completing, I have 12 new activity objects that I need to append to the activities observable array.

Activities definition:

public activities: Observable<Array<ActivitiesItemModel>>;

My initial request:

this.activities = this._transactionService.Get(url)
.map(activities => {
// Creates an activities model which contains items<ActivitiesItemModel>
return new activitiesModel(activities).items;

My infinite scroll request:

// This is where I am stuck..
// I assumed I could just map the values retrieved from the request
.map(a => {
return this._transactionService.Get(queryUrl)
.map(activities => {

return activities;

Any ideas?

Answer Source

This looks like an ideal case for the scan() operator with an empty array as a default value.

This example buffers five values into an array and then merges them with the previous array so it'll continuously print an ever increasing array of values. This should be the same what you're trying to achieve with the infinite scroll:

  .scan((acc, val) => {
    acc = acc.concat(val);
    return acc;
  }, [])
  .subscribe(val => console.log(val));

See live demo:,console

[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Of course you're going to use some remote service instead of Observable.interval() but I think you get the point.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download