如何无限循环数组并显示Angular中的值?

How to loop through an array indefinitely and display the value in Angular?

我有一组单词,我的目标是每隔几秒在 HTML 模板中显示每个单词。结果应该是这样的:https://bootstrapmade.com/demo/iPortfolio/

我知道可以使用以下 JavaScript 代码:

  const typed = select('.typed')
  if (typed) {
    let typed_strings = typed.getAttribute('data-typed-items')
    typed_strings = typed_strings.split(',')
    new Typed('.typed', {
      strings: typed_strings,
      loop: true,
      typeSpeed: 100,
      backSpeed: 50,
      backDelay: 2000
    });
  }

我尝试使用 typescript 复制相同的效果,但我编写了以下代码:

export class HeroComponent implements OnInit {

  words: string[] = ['marco', 'polo'];
  word: string = "";
  constructor() { }

  ngOnInit(): void {
    setTimeout(() => {
    while(true){
      for (let i=0; i < this.words.length; i++) {
        setTimeout(() => {
        this.word = this.words[i];
        console.log(this.word)
      }, 4000)
      };
    }}, 4000);
  }
}

然而,一旦我 运行 网站显示 运行 内存不足。

您能否建议一种巧妙而优雅的方法来实现上面网站中链接的效果?

这样做的方法是:

import { map, timer } from 'rxjs';

@Component({
  ...
})
export class HeroComponent {
  words = ['marco', 'polo'];
  word = timer(0, 4000).pipe(
    map((num) => {
      const index = num % this.words.length;
      const word = this.words[index];
      console.log(word);
      return word;
    })
  );
}

然后在html中使用异步管道:

<p>{{ word | async }}</p>

示例:https://stackblitz.com/edit/angular-ivy-7xbuft?file=src/app/app.component.ts


RxJS 的

timer 从第一个参数 (0ms) 开始按递增顺序 (0, 1, 2, 3, ...) 发出整数,然后每个间隔由第二个参数 (4000ms) 给出).

pipe 让我们在 returning 之前对任何发出的值执行一系列操作。

map 取发出的值而 returns 是一个不同的值,在这种情况下我们使用整数来计算数组的索引,然后 return 该索引处的单词.

async 管道将订阅可观察对象并在组件销毁时取消订阅,从而停止执行。取消订阅对于防止内存泄漏很重要。