使用Angular,Momentjs和Ngx-cookie的倒数计时无法正常工作

时间:2019-01-27 23:47:53

标签: javascript angular cookies momentjs

我正在尝试使用Angular进行从30秒到0的倒计时,但是我正在尝试一些不同的方法。当用户刷新浏览器或转到其他路由器时,我需要倒数才能继续工作。因此,我想到了使用moment.js来获取某人单击按钮并使用ngOnInit的时间来获取保存的cookie并计算倒计时的剩余时间的想法。但是我有一些问题:倒计时有时为负数,有时在更换路由器后返回零。

这是我的代码:

import { Component, OnInit } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

import moment from 'moment';
import { Moment } from 'moment';


@Component({
  selector: 'app-countdown',
  templateUrl: './countdown.component.html',
  styleUrls: ['./countdown.component.css']
})
export class CountdownComponent implements OnInit {

  public isClicked: boolean = false;
  public countDown: number = 30;
  public diffSeconds: number;
  private interval: number;
  private timeSaved: number;
  private clickedSavedTime: number;
  private remainingTime: number;
  private checkCountDownCookie: boolean;
  private checkTimeSaved: boolean;

  constructor(
    private cookies: CookieService
  ) { }

  ngOnInit() {
    this.checkCountDownCookie = this.cookies.check('countDown');
    this.checkTimeSaved = this.cookies.check('timeClick');
    this.clickedSavedTime = +this.cookies.get('timeClick');


    if (this.countDown < 0 || !this.checkCountDownCookie) {
      this.clearAll();
      return;
    }

    if (this.checkTimeSaved) {
      console.log('here');
      this.keepCountdown();

    if (!this.remainingTime || this.remainingTime > 30 || !this.countDown) {
        this.clearAll();
        return;
      }
      this.startCountdown();
      return;
    }
  }

  public startCountdown(): void {
    this.isClicked = true;

    if (!this.checkTimeSaved) {
      this.saveCookie('timeClick', moment().unix());
    }

    this.interval = setInterval(() => {
      if (!this.countDown) {
        this.clearAll();
        return;
      }
      this.countDown --;
      this.saveCookie('countDown', this.countDown);
      console.log(this.countDown);
    }, 1000);

  }

  public saveCookie(name: string, value: number): void {
    this.cookies.set(name, value.toString());
  }

  public clearAll(): void {
    this.cookies.delete('countDown');
    this.cookies.delete('timeClick');
    clearInterval(this.interval);
    this.countDown = 30;
    this.isClicked = false;
  }

  public keepCountdown() {
    this.timeSaved = +moment.unix(+this.cookies.get('timeClick'));
    this.diffSeconds = moment.duration(moment().diff(this.timeSaved)).seconds();
    this.remainingTime = this.countDown - this.diffSeconds;
    this.countDown = this.remainingTime;
  }
}

StackBlitz:https://stackblitz.com/edit/angular-ysizt1?file=src%2Fapp%2Fcomponents%2Fcountdown%2Fcountdown.component.ts

0 个答案:

没有答案