![](/img/trans.png)
[英]Rxjs Observable Interval and Angular2 HTTP: wait for response
[英]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)您想使用.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.