Angular Observable 和 setTimeout 问题 - 输出意外值

问题描述 投票:0回答:1

我的 Angular 代码遇到了涉及 Observables 和 setTimeout 的问题。我的目标是在指定的持续时间内每分钟更新“活动状态”,但我当前的实现产生了意外的结果。当我运行代码时,我得到“2001 分钟前”作为输出,但我不明白为什么?.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  title = 'observable';
  activestatus: any = 'now';
  secondstatus: any = 'now';
  data: any;
  time = 2000;

  ngOnInit(): void {
    this.data = new Observable((observer) => {
      for (var i = 0; i <= this.time; i++) {
        setTimeout(() => {
          observer.next(i + ' minutes ago');
        }, 1000);
      }
    });

    this.data.subscribe((res: any) => {
      this.activestatus = res;
    });
  }
}`

Issue:
I expect to see 'active status' updated every minute for the specified duration. However, the code is not working as intended, and the output is '2001 minutes ago.' I'd appreciate help in understanding and fixing this issue.

Additional Information:

Angular version: 16.2.2
angular typescript settimeout
1个回答
0
投票

您正在创建一个循环,同时设置多个超时。这意味着循环结束后,所有超时将大致在同一时间触发,导致观察者几乎同时发出所有值。

您可以使用 RxJS 提供的

interval
运算符。该运算符以指定的间隔发出连续的数字。

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  title = 'observable';
  activestatus: any = 'now';
  data: any;
  time = 2000;

  ngOnInit(): void {
    this.data = interval(60000) // Emit a value every 60 seconds (1 minute)
      .pipe(
        take(this.time) // Emit values for 'time' number of times
      );

    this.data.subscribe((res: any) => {
      this.activestatus = res + ' minutes ago';
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.