如何在使用javascript完成条件时永久评估变量并执行函数

How to permanently evaluate variables and execute a function when it acomplish a condition with javscript

我从服务器带来了一系列会议。该数组包含 objects 场会议,其中包含会议开始日期时间和会议结束日期时间。我用 ngx 时刻管道显示模板中数组的所有项目,它显示会议开始的剩余时间。我想要做的是,当会议开始时间到达时,将显示一个按钮,以便能够加入会议。也许有一些方法可以永久比较当前日期和会议开始日期,这样当会议到来时我可以自动执行一个功能来显示按钮,而不需要重新加载页面?

您可以创建一个值为 true 或 false 的可观察对象,具体取决于是否应显示加入按钮。

private getShowButtonObservable(m: Meeting): Observable<boolean> {
  const now = new Date();
  if (m.endDate.valueOf() < now.valueOf()) {
    // Meeting has ended, button will never show
    return of(false);
  } else if (m.startDate.valueOf() <= now.valueOf()) {
    // Meeting has started and is in progress
    // show button then hide it at endDate
    return timer(m.endDate).pipe(
      map(() => false), // When timer expires hide the button
      startWith(true) // Start with button shown
    );
  } else {
    // Meeting has not started
    const endTimer$ = timer(m.endDate).pipe(map(() => false));
    const startTimer$ = timer(m.startDate).pipe(map(() => true));
    return concat(startTimer$, endTimer$).pipe(startWith(false));
  }
}

然后您可以使用异步管道 show/hide HTML 中的按钮。例如:

<div *ngFor="let meeting of meetings; let index = index">
  <h2> Meeting #{{ index + 1}} </h2>
   <strong>Start date:</strong> {{ meeting.startDate }}<br />
   <strong>End date: </strong> {{ meeting.endDate }}<br />
   <button *ngIf="meeting.showJoinButton$ | async">Join</button>
</div>

stackblitz 查看完整的工作示例。