Angular 2使用RxJS轮询

Angular 2使用RxJS轮询

问题描述:

我试图轮询一个RESTful端点来刷新我的实时聊天消息。我知道实时聊天的最佳方法是Websockets,我只是想了解RxJS如何与Angular 2配合使用。Angular 2使用RxJS轮询

我想每秒钟检查一次新邮件。我有以下代码:

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

但是我的打字稿transpiler将返回该错误:

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

我使用RxJS 5.0.0-beta.0

如果我使用合并而不是flatMapLatest它根本不调用API。

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

Migrating from RxJS 4 to 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.

+1

如何获得JSON出switchMap的? Typescript正在返回此错误:类型'{}'上不存在属性'json' – AndreFeijo

+0

尝试将'map()'移出,并在'switchMap()'后执行。我没有使用它自己,文档没有任何帮助(; – Sasxa

+5

如果有人想知道如何从switchMap中获取json,你需要输入如下形式:'.map((res:Response) => res.json())'。确保你从**'angular2/http'** – AndreFeijo

为了解释@Sasxa“更多的回答。

插图中的SwitchMap。 (从http://reactivex.io/documentation/operators.html

enter image description here