Angular 在角度模式下每5秒提取一次对象项
我有一组引号,我想选择一个随机引号,每5秒钟显示一次。到目前为止,我已经按如下方式实现了它Angular 在角度模式下每5秒提取一次对象项,angular,typescript,Angular,Typescript,我有一组引号,我想选择一个随机引号,每5秒钟显示一次。到目前为止,我已经按如下方式实现了它 //HTML <div > {{ randomQ.quote }} / {{ randomQ.author }} </div> //TS public quotes: Quotes[] = [ {quote:'Q1',author:'A1}, {quote:'Q2',author:'A2'}, {quote:'Q3',author:'A3'},
//HTML
<div >
{{ randomQ.quote }} / {{ randomQ.author }}
</div>
//TS
public quotes: Quotes[] = [
{quote:'Q1',author:'A1},
{quote:'Q2',author:'A2'},
{quote:'Q3',author:'A3'},
{quote:'Q4',author:'A4'},
];
public index:number = 0;
randomQ: Quotes = this.quotes[0];
ngOnInit() {
setInterval(() => {
this.randomQuote();
}, 5000);
}
randomQuote(){
this.randomQ = this.quotes[(this.index++)%this.quotes.length];
}
//HTML
{{randomQ.quote}/{{randomQ.author}
//TS
公开报价:报价[]=[
{引用:'Q1',作者:'A1},
{引用:'Q2',作者:'A2'},
{引用:'Q3',作者:'A3'},
{引用:'Q4',作者:'A4'},
];
公共索引:编号=0;
randomQ:Quotes=this.Quotes[0];
恩戈尼尼特(){
设置间隔(()=>{
这个。随机引用();
}, 5000);
}
随机引用(){
this.randomQ=this.quotes[(this.index++)%this.quotes.length];
}
但是我担心当索引
超过数字
的限制范围时,这会崩溃。对于简单的函数来说,这似乎太多的代码行了
如何实现这一点?也许您可以使用)API获取随机数
public ngOnInit(){
this.timeout=setInterval(()=>{
this.randomQ=this.getRandomQuote(this.quotes);
}, 5000);
}
private getRandomQuote(引号:Quote[]):Quote{
//也许用Math.random来得到随机数
const randomNumber=Math.floor(Math.random()*quotes.length);
返回引号[随机数];
}
公共恩格德斯特罗(){
//防止内存泄漏
clearTimeout(this.timeout);
}
我认为您可以更轻松地使用随机元素,我看不到任何其他可能的改进。基本上,你有你的集合,你的元素绑定到html和你的代码块,每5秒重置一次。这是你所需要的最低限度