Angular 2 使用 RxJS 进行轮询

Angular 2 polling with RxJS

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

我想每秒检查一次新消息。我有以下代码:

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 转译器返回了这个错误:

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

我正在使用 RxJS 5.0.0-beta.0

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

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

参见 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.

进一步解释@Sasxa 的回答。

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