我有一个REST服务调用,返回约24条记录。我想一次显示5个,每10秒循环一次。以下是我的尝试之一,但这不起作用...
this.http.get<HomeListing[]>(`/api/HomeListing`).subscribe(z => {
const totalCount = z.length;
const pageSize: number = 5;
let currentPage: number = 1;
let endPoint = pageSize;
let exitLoop: boolean = false;
while (true) {
if (currentPage * pageSize > totalCount) {
endPoint = totalCount % pageSize;
exitLoop = true;
} else if (currentPage * pageSize === totalCount) {
exitLoop = true;
}
this.homeListings = z.slice((currentPage - 1) * pageSize, endPoint);
currentPage++;
if (exitLoop)
break;
}
});
有人可以为此指出正确的方向吗?
答案 0 :(得分:2)
如果我没有误解您的要求,那么您必须在10秒钟的间隔内以“ 5”的块为单位获取数组的元素。我用这种方法实现了,看看:
export class AppComponent {
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
startNewTimer = new Subject();
maxImagestoDisplay: number = 5;
slideInterval: number = 10000;
sub: Subscription
ngOnInit() {
let maxCycle = Math.trunc(this.arr.length / this.maxImagestoDisplay);
this.sub = this.startNewTimer.pipe(switchMap( (startVal: number) =>
timer(startVal, this.slideInterval)
),tap(data => {
if (data >= maxCycle) {
this.startNewTimer.next(this.slideInterval)
}
})).subscribe(timerIndex => {
console.log(this.arr.slice(timerIndex * this.maxImagestoDisplay, (timerIndex + 1 ) * this.maxImagestoDisplay));
})
this.startNewTimer.next(0)
}
}
此代码中运行着一个计时器,在生成所有元素之后,该计时器会自行重置(销毁并创建一个新计时器)。 看看是否可以满足要求,请在此处查看示例: