Return 来自 html 调用的 setInterval() 函数的值

Return value from setInterval() function called from html

我想 return 从 html 文件调用的 setInterval() 函数的值。

我知道实际函数没有 returning 任何东西,这就是为什么没有显示该值的原因。但是我如何 return 来自异步函数的值。

代码如下:

.ts:

data = [
    {
      game: "A vs B",
      timeLeft: 123456
    },
    {
      game: "C vs D",
      timeLeft: 342514
    },
    {
      game: "A vs C",
      timeLeft: 654789
    },
    {
      game: "B vs D",
      timeLeft: 978456
    }
  ];
  clearTimeIntervalVar: any;

countdownTime(seconds: number) {
    let hr: any = Math.floor(seconds / 3600);
    let min: any = Math.floor((seconds % 3600) / 60);
    let sec: any = Math.floor((seconds % 3600) % 60);

    this.clearTimeIntervalVar = setInterval(() => {
      sec--;
      if (sec === 0) {
        if (min !== 0) {
          min--;
        }
        sec = 60;
        if (min === 0) {
          hr--;
          min = 59;
        }
      }
      return (
        ("00" + hr).slice(-2) +
        " : " +
        ("00" + min).slice(-2) +
        " : " +
        ("00" + sec).slice(-2)
      );
    }, 1000);
  }

.html:

<div class="flex">
    <div class="width-50">Games</div>
    <div class="width-50">Time Left</div>
</div>
<div class="flex" *ngFor="let item of data">
    <div class="width-50">{{ item.game }}</div>
    <div class="width-50">{{ countdownTime(item.timeLeft) }}</div>
</div>

这里是 stackblitz link

提前致谢。

在您看来,只需显示 {{ item.timeLeft }}{{ secondsToTime(item.timeLeft) }},一个将秒转换为 HH:mm:ss 的实用程序。在您的组件中,编写一个间隔,每秒 item.timeleft 更新一次。

HTML :

<div class="flex" * ngFor="let item of data" >
    <div class="width-50" > {{ item.game }}</div>
    <div class="width-50" > {{ secondsToTime(item.timeLeft) }}</div>
</div>

TS:

data = [
    {game: "A vs B",timeLeft: 123456},
    {game: "C vs D",timeLeft: 342514},
    {game: "A vs C",timeLeft: 654789},
    {game: "B vs D",timeLeft: 978456}
];
clearTimeIntervalVar: any;

launchInterval(){
    setInterval(() => {
        for (let item of data) item.timeLeft--;
    , 1000})
}


secondsToTime(seconds: number) : string{
    let convertedTime;
    // Here convert secons to HH:mm:ss
    return convertedTime
}

Angular烟斗是你的朋友!

@Pipe({ name: "countdown" })
export class CountdownPipe implements PipeTransform {
  transform(time: number) {
    return interval(1000).pipe(map(i => (time - i) * 1000));
  }
}
<div class="width-50">{{ item.timeLeft | countdown | async | date: "HH:mm:ss": "GMT" }}</div>

https://stackblitz.com/edit/angular-ivy-uiluwk?file=src%2Fapp%2Fapp.component.html

我的想法是首先创建一个“可观察的管道”,将您的“时间”值从秒减少到毫秒。然后用“async”管道传输它,使其可被模板读取,然后再次管道传输到 Date,并在 GMT 时间自动格式化。

我没有实现倒计时完成后会发生什么,但您可以通过多种方式在可观察对象中使用“until”运算符或在您的模板中使用三元条件来实现。

Observables 非常强大并且用 Angular 实现得很好。 https://www.learnrxjs.io/ 对掌握 RxJs 很有帮助。

如有任何问题,请联系我