【问题标题】:Angular - interpolating values after every forEach iterationAngular - 在每次 forEach 迭代后插入值
【发布时间】:2022-01-20 18:51:39
【问题描述】:

我正在构建一个 Angular 应用程序,并且我试图在字符串数组的每个 forEach 迭代中插入一个字符串的值。 (quotesData 是我从中获取值的字符串数组)

我的函数如下所示:

export() {
this.quotesData.forEach(element => {
  this.quote = element;
  this.wait(1000); \\ <- manually written function to postpone next line execution for 1s
  console.log(this.quote);
});

}

问题是 {{quote}} 的 HTML 插值中的值在最后一次迭代结束之前不会更新。但是,this.quote 的值会在每次迭代后正确更新并显示在控制台和调试器中。

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    我不确定您的等待功能是如何实现的,但我猜它仍然异步运行。为了解决它,我建议例如将时间增加到 5000 并检查值是否立即显示在控制台中。

    否则,这是一个使用异步等待的工作示例:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'hello',
      template: `<button (click)="display()" >Display</button><h1>Hello {{quote}}!</h1>`,
    })
    export class HelloComponent {
      quotesData: Array<string> = ['A', 'B', 'C'];
      quote: string = '';
    
      wait(ms) {
        return new Promise((res) => setTimeout(res, ms));
      }
    
      async display() {
        for (let quote of this.quotesData) {
          this.quote = quote;
          await this.wait(1000);
          console.log(this.quote);
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 2015-11-25
      • 2018-09-01
      • 2016-04-09
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      相关资源
      最近更新 更多