说我有这个:
isMatchedCountLessThanTotalCountMessage(){
// I want to implement this
// "returns" a string asynchronously
}
getMatchedEventsCount() {
return this.dcs.matchCount.asObservable();
}
getTotalEventsCount() {
return this.dcs.totalCount.asObservable();
}
matchedCount和totalCount是这样的:
public matchCount = new BehaviorSubject<number>(0);
public totalCount = new BehaviorSubject<number>(0);
随着价值观的变化,这些Observable会触发整数。无论何时从任何一个值触发一个值,我想比较两者中最近的两个值,我该怎么做?
我想要做的是从方法
返回一个布尔值所以我可以在HTML中显示:
<div>{{(isMatchedCountLessThanTotalCountMessage() | async)}}</div>
我认为Observable.zip可以解决这个问题:
isMatchedCountLessThanTotalCountMessage(){
return Observable.zip(
this.getMatchedEventsCount(),
this.getTotalEventsCount()
)
.subscribe(function(v){
const intA = v[0];
const intB = v[1];
if(intA > intB)
// but I don't know how to send a message the HTML from here
});
}
答案 0 :(得分:3)
您可以轻松使用.map()
函数转换所需的数据:
isMatchedCountLessThanTotalCountMessage() {
return Observable.combineLatest(
this.getMatchedEventsCount(),
this.getTotalEventsCount(),
)
.map(([intA, intB]) => {
return intA > intB ? '(results ARE filtered)' : '(results are not filtered)'
})
}
答案 1 :(得分:0)
虽然我们可以使用Observable.zip之外的其他东西,但是这样可行。
isMatchedCountLessThanTotalCount() {
return Observable.create(obs => {
return Observable.zip(
this.getMatchedEventsCount(),
this.getTotalEventsCount()
)
.subscribe(v => {
if ((v[1] - v[0]) > 0) {
obs.next('(results ARE filtered)')
}
else {
obs.next('(results are not filtered)');
}
});
});
}
实际上有一种更简单的方法可以使用所谓的“投影函数”:
isMatchedCountLessThanTotalCount() {
return Observable.combineLatest(
this.getMatchedEventsCount(),
this.getTotalEventsCount(),
function (one, two) {
if ((two - one) > 0) {
return '(results ARE filtered)'
}
return '(results are not filtered)';
}
)
}
Observable.combineLatest()
与Observable.zip()
类似,但会触发第一个新值,它不会等待来自所有可观察对象的新值。