Angular 2 polling with RxJS

ε祈祈猫儿з 提交于 2019-12-05 17:15:46

问题


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.


回答1:


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.




回答2:


To explain @Sasxa 's answer a bit more.

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



来源:https://stackoverflow.com/questions/35010182/angular-2-polling-with-rxjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!