【问题标题】:Angular CanDeactivateGuard: How to wait for the right or the next value of an Obersavble?Angular CanDeactivate Guard:如何等待 Observable 的正确值或下一个值?
【发布时间】:2020-02-09 20:29:48
【问题描述】:

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

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 发送?
  • …等到下一个新事件发出?

【问题讨论】:

    标签: angular rxjs observable angular9 candeactivate


    【解决方案1】:

    您可以使用skip 跳过BehaviorSubject 的第一个发射:

    this.service
      .pipe(
        skip(1),
        filter(a => ['accept', 'decline'].includes(a))
      )
    

    【讨论】:

      【解决方案2】:

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

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

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

      我会过滤守卫中的事件:

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

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

      【讨论】:

      • 非常感谢。 filter() 成功了。结合skip(1),这简直是完美的。非常感谢。
      猜你喜欢
      • 2018-08-08
      • 2021-07-17
      • 2021-11-04
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      相关资源
      最近更新 更多