我的一个角度组件需要允许订阅它所拥有的数字。我试图将这个数字变成一个可观察的数字,以便其他人可以订阅它。
我的发布商看起来像
private countChanged = new BehaviorSubject<any>(null);
public historyTimespanChanged$ = this.countChanged.asObservable();
private publish() {
this.countChanged.next(this.count);
}
expandTimeSpan() {
this.count ++;
this.publish();
}
reset() {
this.count = 0;
this.publish();
}
getHistoricalCount() {
return Observable.of(this.count);
}
我的观察者看起来像
this.historyComponent.getHistoricalCount()
.subscribe(count => {
if (count !== 0 ) {
console.log('new history timespan expanded: ', count);
this.historyCount = count;
this.retrieveHistoricalData();
}
});
但订阅者永远不会被调用。 谁能看到我做错了什么?
答案 0 :(得分:1)
我认为代替this.historyComponent.getHistoricalCount()
,您可能意味着this.historyComponent.historyTimespanChanged$.subscribe(...)
,它源自您要发布的BehaviorSubject
。
另一方面,为了避免将this.publish
附加到count
的每个变异上的危险和繁琐,您可能需要查看ReactiveProperty
或使用ES6 setter自行完成:
class HistoryComponent {
...
set count(value: number): bool {
this.countChanged.next(value);
this.count = value;
return true;
}
...
}
答案 1 :(得分:0)
你能分享整个组件吗?因为如果您的订阅只调用一次,其值为0,则if子句将永远不会运行。
getHistoricalCount() {
return Observable.of(this.count);
}
只返回一个只有一个值的Observable:v-|
,您应该尝试返回每this.historyComponent.countChanged
次调用更新的publish
属性。