3

Problem is that: I have simple component, which renders some "history" of messages. When app is loaded, it makes POST-request, gets data and sets data to Observable like this

this.messages$ = Observable.of(messagesAfterPOSTRequest);

where public messages$: Observable<any>;

This data is rendered in template via async pipe:

let message of messages$ | async

It works good, but ....

I get some "new messages" via websocket, so I would like to update the list, which was created on previous step. I am trying to use scan()

this.messages$ = this.messages$.scan((accMessage, numMessage) => {
        console.log("inside current mesages", accMessage, numMessage)
      });

In order to "update" current list messages, but this console.logs looks like never work, even with subscribe()

Eugene Shmorgun
  • 2,083
  • 12
  • 42
  • 67

1 Answers1

1

Use an instance of Subject and push messages into it:

const subject$ = new Subject();

...

subject.next(messagesAfterPOSTRequest);

... then use it a template the same way using async pipe.

Maybe also have a look at ReplaySubject or BehaviorSubject classes if you want to be able to get previous messages as well.

martin
  • 93,354
  • 25
  • 191
  • 226
  • Problem is at start I have list of messages and it's works subject.next(messagesAfterPOSTRequest); but when I get only one message - I get list from one messages, history is removed after next() – Eugene Shmorgun Aug 15 '17 at 09:03
  • Then use the `.scan` operator and add the messages to an array: `.scan((acc, val) => { acc.push(val); return val;}, [])` – martin Aug 15 '17 at 09:06