11

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.

AndreFeijo
  • 10,044
  • 7
  • 34
  • 64

2 Answers2

8

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.

Sasxa
  • 40,334
  • 16
  • 88
  • 102
  • 1
    How do I get the JSON out of switchMap? Typescript is returning this error: Property 'json' does not exist on type '{}' – AndreFeijo Jan 26 '16 at 09:24
  • Try to move `map()` out, and do it after `switchMap()`. I didn't use it myself, and docs aren't any help (; – Sasxa Jan 26 '16 at 09:30
  • 5
    In case anybody is wondering how to get the json out of switchMap, you need to type cast it like this: `.map((res: Response) => res.json())`. Make sure you imported **Response** from **'angular2/http'** – AndreFeijo Jan 27 '16 at 07:41
2

To explain @Sasxa 's answer a bit more.

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

enter image description here

maxisam
  • 21,975
  • 9
  • 75
  • 84