繁体   English   中英

Angular2 rxJS HTTP的可观察间隔-等待时执行某些操作

[英]Angular2 rxJS HTTP Observable Interval - Do something while waiting

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

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)您想使用.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() ,它将显示

暂无
暂无

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

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