使用Angular 2 RC4
运行RxJS 5 beta 6
,我很难搞清楚为什么我的observable不会在订阅者之间共享。我试着仔细按照说明无济于事。我的组件位于下方,但您可以看到它正常运行at this Plunker
模板
<div> Toggle sub 1:
<button (click)="subOne=!subOne">{{subOne?'One is ON ':'One is OFF'}}</button>
</div>
<div> Toggle sub 2:
<button (click)="subTwo=!subTwo">{{subTwo?'Two is ON ':'Two is OFF'}}</button>
</div>
<ul><li *ngFor="let L of log.slice(-16)">{{L}}</li></ul>
类
_subOne = false;
get subOne(){return this._subOne};
set subOne(val){
this._subOne = val;
//if set to true, subscribe
if(val) this.subscriptions.one =
this.source().subscribe(d=>this.print('One sees '+d));
//else, unsubscribe
else this.subscriptions.one.unsubscribe();
}
_subTwo = false;
get subTwo(){return this._subTwo};
set subTwo(val){
this._subTwo = val;
if(val) this.subscriptions.two =
this.source().subscribe(d=>this.print('Two sees '+d));
else this.subscriptions.two.unsubscribe();
}
subscriptions = {'one':null,'two':null};
source(){
return Observable.interval(3000)
.do(()=>this.print("*******EMITTING*******")).share();
}
print(value){this.log.push(value);}
log=[];
输出
我期望订阅者共享相同的observable,因为我使用.share()
运算符。为什么不呢?
答案 0 :(得分:1)
我认为这是因为每次调用source
方法时都会创建一个observable。您需要订阅相同的可观察实例。
source:Observable = this.source(); // <-----
set subOne(val){
this._subOne = val;
if(val) this.subscriptions.one =
this.source.subscribe(d=>this.print('One sees '+d)); // <-----
else this.subscriptions.one.unsubscribe();
}