Angular 2循环遍历列表并有一些延迟

时间:2016-09-29 05:46:03

标签: arrays loops angular typescript

如何使用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>

不会延迟,但会一次循环。

2 个答案:

答案 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)

Plunker example

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;});
  }
}