2016-07-28 93 views
3

運行Angular 2 RC4RxJS 5 beta 6,我很難弄清楚爲什麼我的observable不能在用戶間共享。我試圖按照指示小心無濟於事。我的成份低於,但你可以看到它運行現場at this PlunkerAngular 2和RxJS 5 Observable.share()

模板

<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=[]; 

輸出

enter image description here

由於我使用.share()運營商,我預計用戶共享相同的可觀察性。他們爲什麼不是?

回答

1

我認爲這是因爲您每次調用source方法時都會創建一個可觀察值。您需要訂閱相同的可觀察實例。

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(); 
}