[英]Set Interval on an array in angular project
I'm trying to use the setInterval()
function in order to change text to the user every 3 seconds. 我正在尝试使用setInterval()
函数,以便每3秒将文本更改一次。
I tried looping with for loop but that doesn't work - I see the 'test 03' and that's it. 我尝试使用for循环进行循环,但这不起作用-我看到了“ test 03”,仅此而已。
I can't find a solution. 我找不到解决方案。
export class MessagesComponent implements OnInit { items = ['test 01', 'test 02', 'test 03']; currentItem: any; private interval; constructor() {} ngOnInit() { for (let i = 0; i < this.items.length; i++) { this.interval = setInterval(() => { this.currentItem = this.items[i]; }, 3000); } } }
{{ currentItem }}
Appreciate any help! 感谢任何帮助!
Try it this way instead. 改为尝试这种方式。
pointer
points to the current content you want to display. pointer
指向您要显示的当前内容。 With each interval pointer gets increased by 1 until it has a value > 2. Then it starts with 0 again. 每个间隔指针都增加1,直到其值>2。然后再次从0开始。
export class MessagesComponent implements OnInit {
items = ['test 01', 'test 02', 'test 03'];
currentItem: any;
private pointer: number = 0;
constructor() {}
ngOnInit() {
this.interval = setInterval(() => {
this.currentItem = this.items[this.pointer];
this.pointer++;
if (this.pointer > 2) { this.pointer = 0 };
}, 3000);
}
}
Try this: 尝试这个:
export class MessagesComponent implements OnInit { items = ['test 01', 'test 02', 'test 03']; currentItem: any; private interval; constructor() {} ngOnInit() { for (let i = 0; i < this.items.length; i++) { this.interval = setInterval(() => { this.currentItem = this.items[i]; }, 3000 * i); } } }
{{ currentItem }}
If you are happy with rxjs, 如果您对rxjs满意,
import { timer } from 'rxjs';
import { tap } from 'rxjs/operators';
ngOnInit() {
timer(0, 3000)
.pipe(
tap(v => {
this.currentItem = this.items[v%3]
})
)
.subscribe(console.log);
}
less code, no loop, no fancy logic involved :) 更少的代码,没有循环,没有花哨的逻辑:)
You can do even better with 您可以做得更好
export class MessagesComponent implements OnInit {
private timer$ = timer(0, 3000);
ngOnInit() {
// for loop can be completely removed
}
}
and in html, use 并在html中使用
{{ items[(timer$ | async) % 3] }}
so you literally just use 1 line of code to do the same thing by leveraging async pipe and rxjs, and forget about the ugly for-loop. 因此,您实际上只需使用1行代码就可以利用异步管道和rxjs来完成相同的操作,而不必理会丑陋的for循环。
demo https://stackblitz.com/edit/angular-m5prrk?file=src%2Fapp%2Fapp.component.ts 演示https://stackblitz.com/edit/angular-m5prrk?file=src%2Fapp%2Fapp.component.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.