我有以下订阅服务的组件:
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());
});
}
我有两个问题:
答案 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()