Angular2 rxJS HTTP Observable Interval - 等待时做某事

时间:2016-11-01 16:24:04

标签: angular rxjs

我有以下订阅服务的组件:

this.nodeSummarySubscription = this.netStatusService.getNodeSummary(10000).
    subscribe(
        data => {
            this.offlineNodes = data.NodesFullyDown;
            this.filteredOfflineNodes = data.NodesFullyDown;
            this.nodesOnCellularBackup = data.NodesOn3G;
            this.offlineNodesSubject.next(this.offlineNodes);
            this.cellularNodesSubject.next(this.nodesOnCellularBackup);
            this.incidentNodesSubject.next(data.MonitoredNodes);
            this.isApiCallComplete = true;
            this.myDate = new Date();
            console.log("Refreshed at " + new Date());
        },
        error => console.log(error),
        () => console.log("Call complete")
    );

在我的服务上,在每个指定的时间间隔内执行HTTP调用:

getNodeSummary(interval: number) {
        return Observable.interval(interval).flatMap(() => {
            return this.http.get(this.baseApiUrl + '/HomeApi/NodeSummary/').map(res => res.json());
        });
    }

我有两个问题:

  1. 为什么在页面加载时,我的页面会按照定义的时间间隔进行调用?有没有办法在第一次立即触发HTTPcall,并且只在每隔x个时间间隔后触发它?
  2. 我希望每次数据刷新时都能在页面上显示某种消息(过期时间间隔后的HTTP调用)。是否可以附加Observable上的另一个事件,以便我能够理解定时器过期事件何时被触发?

1 个答案:

答案 0 :(得分:3)

1)您想使用.timer()运算符而不是interval。第一个参数是第一个延迟,第二个参数是触发Observable的时间间隔。

getNodeSummary(interval: number) {
    return Observable.timer(0, interval).flatMap(() => {
        return this.http.get(this.baseApiUrl + '/HomeApi/NodeSummary/').map(res => res.json());
    });
}

2)您应该创建另一个Subject<boolean>,例如loading$,当您开始加载时.next(true),以及呼叫返回时next(false)

private loading$ = new Subject<boolean>();

loadData() {
  this.loading$.next(true);
  this.nodeSummarySubscription = this.netStatusService.getNodeSummary(10000).
      subscribe(
          data => {
            this.offlineNodes = data.NodesFullyDown;
            this.filteredOfflineNodes = data.NodesFullyDown;
            this.nodesOnCellularBackup = data.NodesOn3G;
            this.offlineNodesSubject.next(this.offlineNodes);
            this.cellularNodesSubject.next(this.nodesOnCellularBackup);
            this.incidentNodesSubject.next(data.MonitoredNodes);
            this.isApiCallComplete = true;
            this.myDate = new Date();
            console.log("Refreshed at " + new Date());

            this.loading$.next(false);
        },
        error => console.log(error),
        () => console.log("Call complete")
    );
}

现在,您可以在模板中添加提醒,例如

<div class="alert alert-default" *ngIf="loading$ | async">
   Loading
</div>

如果您拨打loadData()

,就会显示