从一个角度为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 执行,这是记录的内容:
ngOnInit
一发 收到两个 一发 收到三个
一发
收到两个
收到三个
one share 管道制造商中的操作员 two 和 three
one
share
two
three
Source on Stackblitz
这个 share() 操作员在您使用它时进行多播。所以你以前用它的时候 tap 然后 仍有两名观察员。
share()
tap
所以就用 share 之后 它将维护对其父级的一个订阅。
one = this.subject.pipe(tap(e => console.log('one emits')), share());