我有一个调用我的API的服务:
return this._http
.post(apiUrl + 'Controller/Action', params, {withCredentials: true, headers: this.headers})
.timeoutWith(8000, Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
.map((response: Response) => response.json().data);
我从我的组件中调用该函数:
this._mySub = this._myService.getSomething()
.subscribe(
response => this._listOfSomething = response,
error => this._loggerService.log(2, "warn", "Error bla bla")
);
如何在一段时间内运行该HTTP呼叫?
我试过了:
this._mySub = this._myService.getSomething()
.interval(15000)
.startWith(0)
.subscribe(
response => this._listOfSomething = response,
error => this._loggerService.log(2, "warn", "Error bla bla")
);
但那说:
财产'间隔'类型' Observable<任何>'
我有点像这样工作:
Observable.interval(15000).subscribe(() => {
this.refreshList();
});
refreshList() {
this._mySub = this._myService.getSomething()
.subscribe(
response => this._listOfSomething = response,
error => this._loggerService.log(2, "warn", "Error bla bla")
);
}
但是这似乎几乎随机地触发了HTTP调用,并且以这种方式设置它感觉不对。
答案 0 :(得分:0)
您可以尝试这样的事情:
let intervalId = setInterval(() => {
this.updateData();
}, 15000);
updateData(){
this._mySub = this._myService.getSomething()
.subscribe(
response => this._listOfSomething = response,
error => this._loggerService.log(2, "warn", "Error bla bla")
);
}
良好做法是在不需要时清除间隔。您应将时区间隔ngOnInit()
并在ngOnDestroy()
中清除。因为如果你将它放在构造函数中,它将继续更新,即使你将切换组件(转到网站上的另一个子页面)。
EDIT。您可以使用clearInterval(intervalId)
清除间隔。