检测变量何时为 Typescript 中的某个值
Detect when a variable is a certain value in Typescript
我正在处理我的应用程序的不活动超时。当检测到不活动时,将启动一个模态。模态向用户显示一个计时器。当计时器(它是一个计数器)达到 0 时,我希望能够“知道”计数器为 0,这样我就可以实现让用户注销的逻辑。
export class IdleModalComponent implements OnInit {
counter$: Observable<number>;
count = 300 // 5 minutes for the user to respond before we implement the inactivity logic
constructor(public dialogRef: MatDialogRef<IdleModalComponent>) {
this.counter$ = timer(0, 1000).pipe(
take(this.count),
map(() => (--this.count)),
);
}
}
当我在 HTML 中绑定 counter observable 时,它会准确显示倒计时。我只需要能够在以下时间捕获:
this.count === 0
.
是this.counter$
完成的时候。
this.counter$
.subscribe(
() => {}, // each time of count update
() => {}, // error
() => {
// completed and `this.count === 0`
}
)
工作演示
https://stackblitz.com/edit/rxjs-timer-complete?file=src/app/app.component.ts
定时器emit numbers in sequence every specified duration..
地道地使用 map 函数,不要在其中产生任何副作用,只是映射接收到的值。
最后,观察完成:
- 订阅 observable
- 传入完整回调
const initialCounter = 10;
timer(0, 100)
.pipe(
take(initialCounter),
map(v => initialCounter-v))
.subscribe({
next: v => console.log(v),
complete: () => console.log('finished')
});
您可以使用 tap
rxjs 运算符而无需 直接订阅 ,如下所示:
this.counter$ = timer(0, 1000).pipe(
take(this.count),
map(() => (--this.count)),
tap(val => {
if (val === 0) {
// do what you want such as show modal
alert('The count is 0');
}
})
)
我正在处理我的应用程序的不活动超时。当检测到不活动时,将启动一个模态。模态向用户显示一个计时器。当计时器(它是一个计数器)达到 0 时,我希望能够“知道”计数器为 0,这样我就可以实现让用户注销的逻辑。
export class IdleModalComponent implements OnInit {
counter$: Observable<number>;
count = 300 // 5 minutes for the user to respond before we implement the inactivity logic
constructor(public dialogRef: MatDialogRef<IdleModalComponent>) {
this.counter$ = timer(0, 1000).pipe(
take(this.count),
map(() => (--this.count)),
);
}
}
当我在 HTML 中绑定 counter observable 时,它会准确显示倒计时。我只需要能够在以下时间捕获:
this.count === 0
.
是this.counter$
完成的时候。
this.counter$
.subscribe(
() => {}, // each time of count update
() => {}, // error
() => {
// completed and `this.count === 0`
}
)
工作演示
https://stackblitz.com/edit/rxjs-timer-complete?file=src/app/app.component.ts
定时器emit numbers in sequence every specified duration..
地道地使用 map 函数,不要在其中产生任何副作用,只是映射接收到的值。
最后,观察完成:
- 订阅 observable
- 传入完整回调
const initialCounter = 10;
timer(0, 100)
.pipe(
take(initialCounter),
map(v => initialCounter-v))
.subscribe({
next: v => console.log(v),
complete: () => console.log('finished')
});
您可以使用 tap
rxjs 运算符而无需 直接订阅 ,如下所示:
this.counter$ = timer(0, 1000).pipe(
take(this.count),
map(() => (--this.count)),
tap(val => {
if (val === 0) {
// do what you want such as show modal
alert('The count is 0');
}
})
)