我找到了几个可以启动/停止 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/