【发布时间】:2020-03-20 12:52:33
【问题描述】:
我有一个 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 中,并将 messagesQueue 中的 timeoutMessage() 对象转移到消息数组中。
但我觉得这个解决方案并不优雅。有没有一种 RxJS 方法可以通过一些 pipe 运算符以某种方式延迟消息?
【问题讨论】:
标签: javascript angular typescript rxjs observable