【问题标题】:Angular 2 loop through a list with some delayAngular 2 循环遍历列表有一些延迟
【发布时间】:2016-09-29 14:41:33
【问题描述】:

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

不能延迟工作,而是一次循环。

【问题讨论】:

  • 在填充数组之前设置超时
  • @AlekseyL。你能说明一下吗?
  • 您希望在添加整个列表之前还是在添加每个项目之前延迟?
  • @AlekseyL。在添加每个项目之前

标签: arrays loops angular typescript


【解决方案1】:

只需使用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));
    }
}

【讨论】:

  • setTimeout 中断 Angular 变化检测。
  • @Kody 7,不,它没有。至少不是角度 2
  • 一旦你有了生命周期钩子,它就会出现。你不应该在 Angular 中使用 setTimeout。
  • @Kody 你能指出这方面的文档吗?这是setTimeout如何触发角度2中的变化检测blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html的解释
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2014-06-26
    • 2019-05-26
    • 2013-06-22
    • 1970-01-01
    相关资源
    最近更新 更多