使用RxJS进行Angular 2轮询 [英] Angular 2 polling with RxJS

查看:252
本文介绍了使用RxJS进行Angular 2轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试轮询RESTful端点以刷新我的实时聊天消息.我知道进行实时聊天的最佳方法是Websockets,我只是想了解RxJS如何与Angular 2配合使用.

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));
   });

但是我的Typescript编译器返回此错误:

However my Typescript transpiler is returning this error:

类型'Observable< number>'上的属性'flatMapLatest'不存在

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

我正在使用RxJS 5.0.0-beta.0

I'm using RxJS 5.0.0-beta.0

如果我使用 merge 而不是 flatMapLatest ,它根本不会调用API.

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

推荐答案

您需要使用switchMap(),RxJS 5中没有flatMapLatest().

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

请参见从RxJS 4迁移到5 .尽管文档对switchMap() ...

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

通过将提供的函数应用于源Observable发出的每个项目(返回一个Observable),然后再发射这些Observable中最近发射的项目,来返回新的Observable.

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.

这篇关于使用RxJS进行Angular 2轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆