Observable 不调用 complete() 方法

Observable does not call complete() method

注意:我知道有一个来自 rxjs 的可观察计时器,我将其用作概念证明以了解可观察对象的工作原理。

我在 angular 中创建了一个计时器,它有一个启动按钮、一个带有秒数的文本和一个带有状态 (stopped/executing/finished) 的文本。

当我点击按钮时,当前示例开始运行,状态变为“正在执行”,秒数发生变化。但是当它达到 5 时,它会停止(显示“完成”日志并且秒数不再更改)但状态不会更改为“完成”(并且“完成”控制台日志也不会出现)。而且error方法也不执行。

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

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

  public time: number = 0;
  public state: string = "Stopped";
  private crono = new Observable<number>(
    observer => {
      let start: number = (new Date()).getTime();
      let lastCount = 0;
      (function repeat() {
        let now: number = (new Date()).getTime();
        let seconds = ((now - start) / 1000 | 0);
        if (lastCount < seconds) {
          observer.next(seconds);
          if (seconds >= 5) {
            console.log("Finishing");
            return;
          }
          lastCount = seconds;
        }
        setTimeout(
          repeat,
          100);
        })();
    });

  constructor() { }

  ngOnInit(): void {
  }

  onStart(): void {
    console.log("Starting");
    let self = this;
    this.state = "Executing";
    this.crono.subscribe({
      next(seconds: number) {
        console.log(`At next ${seconds}`);
        self.time = seconds;
      },
      error(err) {
        console.log("Error");
      },
      complete() {
        console.log("Finished");
        self.state = "Finished";
      }
    })
  }
}

和html

<button (click)="onStart()">Start</button>
<div>{{time}}</div>
<div>{{state}}</div>

您需要调用 observer.complete() 来告诉订阅者操作​​已完成。

if (seconds >= 5) {
        console.log("Finishing");
        observer.complete();
        return;
      }