Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 polling with RxJS

I'm trying to poll a RESTful endpoint to refresh my live chat messages. I know the best approach for a live chat would be Websockets, I'm just trying to understand how RxJS works with Angular 2.

I want to check for new messages every second. I have the following code:

return Rx.Observable
   .interval(1000)
   .flatMapLatest(() => this.http.get(`${AppSettings.API_ENDPOINT}/messages`))
   .map(response => response.json())
   .map((messages: Object[]) => {
      return messages.map(message => this.parseData(message));
   });

However my Typescript transpiler is returning this error:

Property 'flatMapLatest' does not exist on type 'Observable<number>'

I'm using RxJS 5.0.0-beta.0

If I use merge instead of flatMapLatest it doesn't call the API at all.

like image 290
AndreFeijo Avatar asked Jan 26 '16 09:01

AndreFeijo


2 Answers

You need to use switchMap(), there's no flatMapLatest() in RxJS 5.

See Migrating from RxJS 4 to 5... Although docs aren't very clear about switchMap()...

Returns a new Observable by applying a function that you supply to each item emitted by the source Observable that returns an Observable, and then emitting the items emitted by the most recently emitted of these Observables.

like image 123
Sasxa Avatar answered Nov 18 '22 09:11

Sasxa


To explain @Sasxa 's answer a bit more.

SwitchMap in illustration. (from http://reactivex.io/documentation/operators.html)

enter image description here

like image 37
maxisam Avatar answered Nov 18 '22 11:11

maxisam