我有一个 SnackbarComponent,它负责为用户显示带有信息的 Snackbar。通知来自我在 SnackbarComponent
中订阅的 NotificationService .传入的消息被推送到消息数组并在 3 秒后从它转移。在我的 html 模板中,我遍历消息并显示它们。
export class SnackbarComponent implements OnInit, OnDestroy {
private notificationSubscription: Subscription;
messages: NotificationMessage[] = [];
constructor(private notificationService: NotificationService) {
}
ngOnInit() {
this.notificationSubscription = this.notificationService.notification$
.subscribe(
(message: NotificationMessage) => {
this.messages.push(message);
setTimeout(() => {
this.messages.shift();
}, 3000);
}
)
}
ngOnDestroy(): void {
this.notificationSubscription.unsubscribe();
}
问题是,我想一次只显示 3 条消息并延迟其他消息(如果当前少于 3 条消息,则立即显示)。
我有一个看起来像这样的工作解决方案:
private notificationSubscription: Subscription;
messages: NotificationMessage[] = [];
messagesQueue: NotificationMessage[] = [];
ngOnInit() {
this.notificationSubscription = this.notificationService.notification$
.subscribe(
(message: NotificationMessage) => {
if (this.messages.length < 3) {
this.messages.push(message);
this.timeoutMessage();
} else {
this.messagesQueue.push(message);
}
}
)
}
private timeoutMessage() {
setTimeout(() => {
this.messages.shift();
if (this.messagesQueue.length > 0) {
this.messages.push(this.messagesQueue.shift());
this.timeoutMessage();
}
}, 3000);
}
如果有 3 条或消息,则将新消息推送到 messagesQueue 和
timeoutMessage()
中来自 messagesQueue
的对象被转移到消息数组。但我觉得这个解决方案并不优雅。有没有一种 RxJS 方法可以通过一些
pipe
以某种方式延迟消息?运营商?
最佳答案
您可以使用 延迟 运算符或条件延迟 延迟时间根据条件延迟
import {delay} from 'rxjs/operators';
this.notificationService.notification$.pipe(
delay(3000)
).subscribe();
以 为例延迟时间
this.notificationService.notification$.pipe(
delayWhen(message => this.messages.length < 3 ? interval(0) : interval(3000))
).subscribe();
关于javascript - RxJS:延迟传入的 observables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59028303/