Eugene Shmorgun
Eugene Shmorgun

Reputation: 2075

How can I update Observable, which used in async pipe?

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()

Upvotes: 3

Views: 2751

Answers (1)

martin
martin

Reputation: 96969

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.

Upvotes: 1

Related Questions