代码之家  ›  专栏  ›  技术社区  ›  Lucas Dmnt

rxjsTimer/observable subscribe的角度倒计时

  •  0
  • Lucas Dmnt  · 技术社区  · 7 年前

    角度5。

    我正在进行现场聊天。

    用户可以聊天,直到倒计时达到0。

    第一个用户输入后,开始倒计时:

    private engage_session() {
    
    if(!this.is_engaged){
    
      this.countDown = Observable.timer(0, 1000)
        .take(this.counter)
        .map( () => --this.counter );   
    
      this.countDown.subscribe( remaining_credit => { this.remaining_credit = remaining_credit } );  
    }
    
    this.is_engaged = true;
    
    }
    

    我需要订阅倒计时,以便在其他函数中使用它:

    public sendMessage(message: Message): void
      {
        this.engage_session();
    
        if (!message) { return; }
    
        this.socketService.send({
          from: this.tokenUser.username,
          content: message,
          created_at: moment().format(),
          remaining_credit: this.remaining_credit || this.counter,
        });
        this.messageContent = null;
      }
    

    我在模板中也有类似的内容:

     CountDown : <span class="badge badge-light">{{countDown | async | formatTime }}</span>
    

    问题是:当我订阅倒计时时,计时器的速度是应该的两倍。

    但当我删除该行时:

    this.countDown.subscribe( remaining_credit => { this.remaining_credit = remaining_credit } );
    

    然后倒计时开始了。。

    感谢您的帮助=)

    1 回复  |  直到 7 年前
        1
  •  0
  •   Julius Dzidzevičius    7 年前

    它的速度可能会快一倍,因为你订阅了两次( async 是您的第二个订阅)。我不完全了解您的结构和实现,但我认为您可以简单地做到:

    CountDown : <span class="badge badge-light">{{remaining_credit | formatTime }}</span>

    如果此HTML来自创建 countDown 可观察到