我有两个Observable,第二个Observable(convertScore $)需要使用第一个Observable的返回值(displayScore $)。
我使用do运算符可以组合两个主要的Observerbles,但是第二个do运算符(函数:fakeImgSrcFromHttp)在第一个Observable(displayScore $)内部不能执行,为什么??
我预计结果是:
这是我的代码,或you can view it from JSBIN
/***** From A Service *****/
var convertScore$ = fakeScoreFromHttp()
.do(score => covertScoreToOtherData(score))
.do(score => {
fakeImgSrcFromHttp(score)
.do(imgSrc => {
console.log("bind ImgSrc to HtmlTag:" + imgSrc);
})
});
function fakeScoreFromHttp(){
return Rx.Observable.of(100);
}
function fakeImgSrcFromHttp(score){
// ToDo : if score is something, then do else do....
// return
return Rx.Observable.of("it's a src string");
}
function covertScoreToOtherData(score){
console.log("covert score:" + score + " To OtherData")
}
/***** From B Service *****/
var displayScore$ = convertScore$.do(score => displayScore(score));
displayScore$.subscribe({
// next: (value) => { },
// error: (err) => { console.log('Error: ' + err); },
complete: (score) => {
console.log('complete');
}
});
function displayScore(score){
console.log("display score:"+score);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.js"></script>
&#13;
答案 0 :(得分:0)
使用运算符 - flatMap
var example = fakeScoreFromHttp()
.do(score => covertScoreToOtherData(score))
.flatMap(score => {
return fakeImgSrcFromHttp(score)
.do(imgSrc => {
console.log(imgSrc);
})
});
example.subscribe({
// next: (value) => { console.log(value); },
// error: (err) => { console.log('Error: ' + err); },
// complete: () => { console.log('complete'); }
});
function fakeScoreFromHttp(){
return Rx.Observable.of(100);
}
function fakeImgSrcFromHttp(score){
// ToDo : if score is something, then do else do....
// return
return Rx.Observable.of("it's a src string");
}
function covertScoreToOtherData(score){
console.log("covert score:" + score + " To OtherData")
}
答案 1 :(得分:0)
current_user.reload
/***** From A Service *****/
var convertScore$ = fakeScoreFromHttp()
.do(score => covertScoreToOtherData(score))
.flatMap(score => {
return fakeImgSrcFromHttp(score)
.do(imgSrc => {
console.log("bind ImgSrc to HtmlTag:" + imgSrc);
})
});
function fakeScoreFromHttp(){
return Rx.Observable.of(100);
}
function fakeImgSrcFromHttp(score){
// ToDo : if score is something, then do else do....
// return
return Rx.Observable.of("it's a src string");
}
function covertScoreToOtherData(score){
console.log("covert score:" + score + " To OtherData")
}
/***** From B Service *****/
var displayScore$ = convertScore$.do(score => displayScore(score));
displayScore$.subscribe({
// next: (value) => { },
// error: (err) => { console.log('Error: ' + err); },
complete: (score) => {
console.log('complete');
}
});
function displayScore(score){
console.log("display score:"+score);
}