yorozuya
yorozuya

Reputation: 15

make an event happen at specific time

I've got a booking app. The user can book an appointment. For that he will choose an hour (let's say 4PM) and a part of the app will be available for him at 4PM. I've got a button "Use" that is usable at the time of the booking.

Do you know a way to make my button usable without having to refresh the page constantly ? I've got around 50 users and a lot of bookings so I can't refresh the page constantly to make the button usable. Is there a way to do that ?

For the moment I'm using interval to refresh the page every minute. I don't have any code to display as I don't have any idea how to make that possible.

html :

    <div *ngIf="
        (bookings.startDate | date: 'HH:mm') <= startTime &&
        (bookings.endDate | date: 'HH:mm') > startTime">
      <button (click)="selectedBook(bookings)">
        Use
      </button>
    </div> 

ts :

const todayDate = new Date();
this.startTime = this.datePipe.transform(todayDate, 'HH:mm');

  selectedBook(booking) {
    const id = booking.id;
    this.router.navigate([`./place/${id}`]);
  }

Upvotes: 0

Views: 688

Answers (1)

Joshua McCarthy
Joshua McCarthy

Reputation: 1852

I would setup an observable that emits a boolean value based on your condition. And have that wrapped inside an interval that emits every second (or longer if need be).

public canBook$ = interval(1000).pipe(
  mapTo(new Date()),
  map(now => (this.bookings.startDate <= now) && (this.bookings.endDate > now)),
  distinctUntilChanged()
);

If the date formats do not match, you can add another map() to convert the new Date() into the format you need before checking the conditional.

The distinctUntilChanged() operator ensures the observable doesn't keep emitting false every second. It will only emit a new value if it is different from the previous one.

Then in your template file.

<div *ngIf="canBook$ | async">
  <button (click)="selectedBook(bookings)">
    Use
  </button>
</div> 

Upvotes: 2

Related Questions