0

我正在构建一个通知组件,它应该向用户显示通知。当一次创建多个通知时,它应该将它们排队。

现在它可以很好地显示第一个通知,但之后它会同时触发 2 个通知(请参见下面的当前输出)。它不会等待上一个通知显示然后在显示下一个通知之前再次隐藏。

通知.api.ts

public notifications = new Subject<INotificationEvent>();
public notifications$ = this.notifications.asObservable();

通知.component.ts

private finished = new Subject();

constructor(private notifications: NotificationsApi) {}

zip(this.notificationsApi.notifications$, this.notificationsApi.notifications, (i, s) => s).pipe(
  tap(() => {

    if (!this.isActive) {
      this.finished.next();
    }
  }),
  delayWhen(() => this.finished),
  delay(450),
  tap((event: INotificationEvent) => {
    this.notification = event;
    this.isActive = true;
    this.cd.markForCheck();
    console.log(this.notification);
    console.log('showing');
  }),
  delay(this.hideAfter),
  tap(() => {
    this.isActive = false;
    this.cd.markForCheck();
    console.log('closing');
  }),
  delay(450)
).subscribe(() => {
  console.log('finishing');
  this.finished.next();
});

app.component.ts

let i = 0;
setInterval(() => {
  this.notifications.newNotification({message: `${i}`, theme: 'primary'});
  i++;
}, 2000);

电流输出

{message: "0", theme: "primary"}
showing
closing
finishing
{message: "1", theme: "primary"}
showing
{message: "2", theme: "primary"}
showing
closing
finishing
{message: "3", theme: "primary"}
showing
{message: "4", theme: "primary"}
showing
closing
closing
finishing
finishing
{message: "5", theme: "primary"}
showing
{message: "6", theme: "primary"}

期望的输出

{message: "0", theme: "primary"}
showing
closing
finishing
{message: "1", theme: "primary"}
showing
closing
finishing
{message: "2", theme: "primary"}
showing
closing
finishing
{message: "3", theme: "primary"}
showing
closing
finishing
{message: "4", theme: "primary"}
showing
closing
finishing
{message: "5", theme: "primary"}
showing
closing
finishing
{message: "6", theme: "primary"}
showing
closing
finishing

我怎样才能解决这个问题?

4

1 回答 1

2

根据您的描述,在我看来,您可以使用concatMap和轻松实现相同的目标delay

在这个例子中,每一次按钮点击都代表一个通知。每个通知需要 2 秒。这取决于您想在观察者中做什么,但如果您根本不需要通知,您可以将其留空(否则您可能需要startWith)。多个通知在里面排队concatMap,一个接一个地执行。

const notification$ = fromEvent(document.getElementsByTagName('button')[0], 'click');

notification$.pipe(
  concatMap(event => of(event).pipe(
    tap(v => console.log('showing', v)),
    delay(2000),
    tap(v => console.log('closing', v)),
  ))
).subscribe();

现场演示:https ://stackblitz.com/edit/rxjs-nqtfzm?file=index.ts

于 2019-02-24T14:52:18.310 回答