简体   繁体   English

使用RxJS进行Angular 2轮询

[英]Angular 2 polling with RxJS

I'm trying to poll a RESTful endpoint to refresh my live chat messages. 我正在尝试轮询RESTful端点以刷新我的实时聊天消息。 I know the best approach for a live chat would be Websockets, I'm just trying to understand how RxJS works with Angular 2. 我知道实时聊天的最佳方法是Websockets,我只是想了解RxJS如何与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: 但是我的Typescript转换器返回了这个错误:

Property 'flatMapLatest' does not exist on type 'Observable<number>' 属性'flatMapLatest'在'Observable <number>'类型中不存在

I'm using RxJS 5.0.0-beta.0 我正在使用RxJS 5.0.0-beta.0

If I use merge instead of flatMapLatest it doesn't call the API at all. 如果我使用merge而不是flatMapLatest,它根本不会调用API。

You need to use switchMap() , there's no flatMapLatest() in RxJS 5. 你需要使用switchMap() ,在RxJS 5中没有flatMapLatest()

See Migrating from RxJS 4 to 5 ... Although docs aren't very clear about switchMap() ... 请参阅从RxJS 4迁移到5 ...尽管有关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. 通过应用一个函数返回一个新的Observable,该函数提供给返回Observable的源Observable发出的每个项目,然后发出这些Observable最近发出的项目。

To explain @Sasxa 's answer a bit more. 解释一下@Sasxa的答案。

SwitchMap in illustration. SwitchMap在插图中。 (from http://reactivex.io/documentation/operators.html ) (来自http://reactivex.io/documentation/operators.html

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM