考虑这段来自 Angular 6 组件的代码:
class AppComponent {
subject = new Subject<any>();
one = this.subject.pipe(share(), tap(e => log('one emits')));
two = this.one.pipe(tap(e => log('two emits')));
three = this.one.pipe(delay(500), tap(e => log('three emits')));
ngOnInit() {
this.two.subscribe(e => log('two received'));
this.three.subscribe(e => log('three received'));
this.subject.next();
}
}
当 ngOnInit
执行时,这是记录的内容:
one emits
two emits
two received
one emits
three emits
three received
我不明白:为什么 one
发出两次?管道中的 share
运算符不应该让 two
和 three
订阅相同的共享源吗?
最佳答案
share()
运算符在您使用它时进行多播。所以当你在 tap
之前使用它时,tap
仍然有两个观察者。
所以只需在 tap
之后使用 share
,它就会维护一个对其父级的订阅。
one = this.subject.pipe(tap(e => console.log('one emits')), share());
关于angular - RxJS 可观察对象 : why does callback fire twice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51876752/