我有一个发出事件的服务:
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
。
我怎样才能让它工作,以便它:
- ...等待
接受
或拒绝
发送? - ...等到下一个新事件发出?
最佳答案
您可以使用 skip
跳过 BehaviorSubject
的第一次发射:
this.service
.pipe(
skip(1),
filter(a => ['accept', 'decline'].includes(a))
)
关于Angular CanDeactivate Guard : How to wait for the right or the next value of an Obersavble?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141007/