Ionic2中有多个$ http请求,间隔时间

时间:2017-01-25 08:50:17

标签: http ionic2 observable intervals

我想将多个http请求分成一个observable,按间隔调用它,并在所有订阅者之间共享相同的数据。

到目前为止,我的代码看起来像这样:

import {Observable} from "rxjs/Rx";

let obs = Observable
    .interval(10000)
    .publish()
    .connect()
    .forkJoin(
      this.http.get(API_URL + "x", {headers: this.headers})
        .map(response => response.json()),
      this.http.get(API_URL + "y", {headers: this.headers})
        .map(response => response.json())
    )
    .map(res => {
     // do some stuff
     return res;
    });

错误:

Typescript Error
Property 'forkJoin' does not exist on type 'Subscription'.

我读过:

https://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html

Multiple $http requests in Ionic2

http://restlet.com/blog/2016/04/12/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-2/

谢谢!

1 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

let source = Observable
    .interval(1000)
    .flatMap(() => {
        return Rx.Observable.forkJoin(
            this.http.get(API_URL + "x", {headers: this.headers})
                .map(response => response.json()),
            this.http.get(API_URL + "y", {headers: this.headers})
                .map(response => response.json())
        )
    })
    .publish();

source.connect();

然后观察者订阅了这个可观察的

source.subscribe(...);

我在这里做的是采用可观察的间隔并替换所有操作的forkJoin的每个值。然后发布它以将相同的数据共享给许多订阅。

您在实施中遇到的另一个问题是您从.connect()返回订阅,这只是为了在您需要时处理它(取消订阅)。观察员应订阅已发布的来源。