gpt4 book ai didi

Angular 2 和 RxJS 5 Observable.share()

转载 作者:太空狗 更新时间:2023-10-29 19:31:00 26 4
gpt4 key购买 nike

使用 RxJS 5 beta 6 运行 Angular 2 RC4,我很难弄清楚为什么我的 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=[];

输出

enter image description here

自从我使用 .share() 运算符以来,我希望订阅者共享相同的可观察对象。为什么不是?

最佳答案

我认为这是因为每次调用 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();
}

关于Angular 2 和 RxJS 5 Observable.share(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38638074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com