如何使用Angular 2和TypeScript在数组中循环延迟?
我有一个数组,
students: Array<any> = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
我想遍历列表并显示2000ms
延迟的名称。
<div *ngFor="let student of students">
{{student.name}}
</div>
不会延迟,但会一次循环。
答案 0 :(得分:5)
只需使用setTimeout
即可。例如(*未测试):
students: Array<any> = [ ];
populateArrayWithDelay():void{
let people = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
for(let i = 0; i < people.length; i++){
let student = people[i];
setTimeout(() => {
this.students.push(student);
}, 2000*(i+1));
}
}
答案 1 :(得分:1)
export class App {
name:string;
students: Array<any> = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
constructor() {
var timer = 0;
this.$students = Observable.from([[], ...this.students])
.mergeMap(x => Observable.timer(timer++ * 1000).map(y => x))
.scan((acc, curr) => {acc.push(curr); return acc;});
}
}