我有用户observable.timer每隔一分钟后获取数据。下面是代码
getNewData(){
var catId = this.serv.getSelectedCategory();
var sinceId = this.myArray[0].userdataId;
var dataurl = '';
if (catId < 0) {
dataurl = this.baseUrl + '?bookMarked=' + isBookmarked + '&count=' + this.count + '&isPrevious=' + isPrevious + '&sinceId=' + sinceId;
}
else {
dataurl = this.baseUrl + 'company/' + catId + '/abc' + '?bookMarked=' + isBookmarked + '&count=' + this.count + '&isPrevious=' + isPrevious + '&sinceId=' + sinceId;
}
var self = this;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', token);
return Observable.timer(60000,60000)
.switchMap(() => this.http.get(dataurl , { headers: headers, method: 'GET' }))
.map((res: Response) => {
var obj = res.json();
return obj;
});
}
在组件中
this.newDataSubscription = this.testServ.getNewData(false,false).subscribe(data => {
this.newdataArray = this.serv.newdataArray ;
})
问题是每次定时器执行时都会触发相同的url。我想根据获取的新数据更新url中的sinceId。
因此每次定时器执行时,SinceId必须是数组的第0个元素。
请指南
答案 0 :(得分:0)
似乎this.myArray
是您的ID的来源以及您希望在请求中包含哪些ID。
getNewData() {
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', token);
return Observable.timer(60000,60000)
.switchMap(() => {
this.myArray.forEach(e => {
// you can avoid too many vars, they are here just with purpose of clarification
const sinceId = e.userdataId;
const dataurl = buildUrl(e.userdataId);
return this.http.get(dataurl , { headers: headers, method: 'GET' }) ;
});
})
.map((res: Response) => {
var obj = res.json();
return obj;
});
}
buildUrl(sindeId) {
const catId = this.serv.getSelectedCategory();
let dataurl = '';
if (catId < 0) {
dataurl = `${this.baseUrl}?bookMarked=${isBookmarked}&count=${this.count}&isPrevious=${isPrevious}&sinceId=${sinceId}`;
}
else {
// be careful here, you are hardcoding '/abc'
dataurl = `${this.baseUrl}company/${catId}/abc?bookMarked=${isBookmarked}&count=${this.count}&isPrevious=${isPrevious}&sinceId=${sinceId}`;
}
return dataurl;
}