angular - 如何停止 rxjs 间隔/计时器

标签 angular rxjs intervals

我找到了几个可以启动/停止 rxjs 计时器或间隔的示例,但是我无法让我的计时器停止。

下面的 HTML 片段:

仅供引用:第一次按下 autoPlay() 将触发我的自动播放间隔。再次点击将关闭自动播放。

我的 Angular (click) 事件将触发 autoPlay() 就好了,我的 this.toggleMe 按预期工作(翻转值之间每 1 秒 true 和 false)。

<mat-slide-toggle #toggleMe color="primary" [checked]="toggleMe"></mat-slide-toggle>
<div>
  <mat-icon svgIcon="auto-flipper" (click)="autoPlay()"></mat-icon>
</div>

<!-- example of the two panels that are shown/hidden based on slide-toggle above -->
<show-panel-one
  [hidden]="toggleMe.checked"
></show-panel-one>

<show-panel-two
  [hidden]="!toggleMe.checked"
></show-panel-two>

但是,我正试图通过 Subject 清除间隔;即,this.stopPlay$.next();。但它不会停止间隔。

import { Component, ... } from "@angular/core";

@Component({
    selector: "auto-play",
    templateUrl: "./auto-play.component.html",
})

export class MyTestComponent implements OnChanges, OnInit {

autoPlay = false;
stopPlay$: Subject<any> = new Subject();
@ViewChild("examToggle") examToggle: MatSlideToggle;

constructor() {}

autoPlay(): void {
	this.autoPlay = !this.autoPlay;
	if (!this.autoPlay) {
		this.stopPlay$.next();
	}
	const autoPlayInter = interval(1000);
	autoPlayInter.subscribe(() => {
		this.toggleMe.checked = !this.toggleMe.checked;
	});
	autoPlayInter.pipe(
		// map((_) => {}),
		takeUntil(this.stopPlay$),  // Shouldn't the .next() above trigger the timer stop ?
	);        
 }
 
}

如果知道我做错了什么就好了。

我的一些引用:

How to stop rxjs timer Restart the timer on an rxjs interval

* 更新 - 最终版本 *

autoSwitch(): void {
        this.autoPlay = !this.autoPlay;

        if (this.autoPlay) {
            this.autoPlayInter = timer(0, 2000)
                .pipe(
                    takeUntil(this.stopPlay$),
                    tap((_) => (this.toggleMe.checked = !this.toggleMe.checked)),
                )
                .subscribe();
        } else {

            this.stopPlay$.next(); // this stops the timer
        }
    }

最佳答案

回答更新后的代码:

应该更改为如下内容:

autoPlay() {
    this.autoPlay = !this.autoPlay;

    if (this.autoPlay) {
        this.autoPlayInter = interval(2000);
        this.autoPlayInter
            .pipe(takeUntil(this.stopPlay$))
            .subscribe(() => {
                this.examToggle.checked = !this.examToggle.checked;
            });
    } else {
        this.stopPlay$.next();
    }
 }

关于angular - 如何停止 rxjs 间隔/计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56174610/

相关文章:

r - findInterval() 在 data.table R 中具有不同的间隔

javascript - 如何设置 5 秒后特定功能的间隔

angular - 如何使用 Angular Module Federation 导入整个应用程序

javascript - 如何使用 RxJS 避免过长的 if else 语句

html - 带有 Z-Index 和下拉列表的 CSS 垂直导航问题

RXJs 服务返回多个 observables

RxJS 从 mergeMap 返回值数组

mysql - 与 MySQL 合并间隔

Angular 6 - 隐藏或显示从服务触发的组件中的 Div

javascript - 将外部 CSS 和 JS 链接添加到 Angular 2 中的组件