2

我有一个发出事件的服务:

export class MyService {
  private event = new BehaviorSubject<string>('init');
  event$ = this.event.asObservable();

  constructor() { }

  update(): void {
    this.event.next('update');
  }

  accept(): void {
    this.event.next('accept');
  }

  decline(): void {
    this.event.next('decline');
  }
}

我还有一个CanDeactivateGuard由组件中的函数触发的:

canDeactivate(): Observable<boolean> {
  return this.service.event$.pipe(
    map(action => {
      return action === 'accept';
    })
  )
}

现在这一切正常。但我有一个问题:

这将始终返回最后一个事件。所以当什么都没有发生时,它会init立即发送。如果update()被调用,它将update直接发送。

我怎样才能使它工作,以便它:

  • ... 等到acceptdecline正在发送?
  • ... 等到下一个新事件发出?
4

2 回答 2

1

您正在接收初始事件,因为它是一个 BehaviorSubject。

您正在接收所有事件,因为您没有将它们过滤掉。

你如何处理这取决于 event$ 服务的目的。如果发出所有事件(包括初始状态)很重要,那么绝对将其作为行为主体。

我会过滤警卫中的事件:

canDeactivate(): Observable<boolean> {
  return this.service.event$.pipe(
    filter(action => action === 'accept' || action === 'decline'),
    map(action => {
      return action === 'accept';
    })
  );
}

这具有忽略所有不是“接受”或“拒绝”的内容的效果。

于 2020-02-09T20:34:25.623 回答
1

您可以跳过BehaviorSubjectwith的第一个发射skip

this.service
  .pipe(
    skip(1),
    filter(a => ['accept', 'decline'].includes(a))
  )
于 2020-02-09T20:35:43.577 回答