我已經創建了測試Observables
兩個函數傳遞數據,每個返回Observable
:這樣一種更好的方式,從一個可觀察到另一個
foo() {
return new Observable(observer => {
let i = 0;
setInterval(() => {
if(i === 10) {
observer.complete();
} else {
observer.next(i);
i++;
}
}, 1000);
// If I call observer.complete() here then it never completes
});
}
bar(fooResult) {
return new Observable(observer => {
let j = 0;
setInterval(() => {
if(fooResult) {
observer.next('j -> '+j+' plus fooResult '+JSON.stringify(fooResult));
observer.complete();
} else {
observer.next(j);
j++;
}
}, 2000);
});
}
,並利用其中的一部分:
let fooResult = [];
// Testing observables...
this.exampleProductService.foo().subscribe(
(res) => {
console.log('foo next() -> '+res);
fooResult.push(res);
},
(err) => {
console.error('foo error: '+JSON.stringify(err));
},
() => {
console.log('foo finished');
this.exampleProductService.bar(fooResult).subscribe(
(res) => {
console.log('bar next() -> '+res);
},
(err) => {
console.error('bar error: '+JSON.stringify(err));
},
() => {
console.log('bar finished');
}
);
}
);
提出問題的人:
有沒有更好的方法來傳遞數據完成另一個函數的Observable,該函數也返回一個Observable?建立一個數組似乎麻煩,我不能做以下爲
Observable
的complete callback
部分不傳遞參數一樣progressUpdate
和onError
:(complete) => { this.exampleProductService.bar(complete).// rest of code }
我試圖指派第一功能的結果一個變量,然後傳遞該變量,但如預期的那樣,我得到了一個Observable,而不是我想要的結果。
關於我如何進行上述操作,有什麼不正確的嗎?
感謝
附:這是一個Angular 2應用程序!
感謝feedbacl保羅。在這種情況下,您如何特別擺脫全球狀態? – Katana24
另外 - 你能解釋一下這條線多一點嗎? .reduce((total,diff)=> [... total,diff],[])從文檔中,它充當Observable上的累加器,並在我完成時返回一個值。我明白,但可選的種子提供(差異)是什麼,以及[...總,差異]是什麼意思 - 我以前從來沒有見過這樣的:全局狀態 – Katana24
,不再有一個全局數組叫做' fooResult'。 re:語法,'[... total,diff]'是'total.concat([diff])'的ES6短手,基本上它會創建一個新的數組副本加上新的項目以避免變化現有的項目。 'diff'是進入的新值,而不是可選的種子,它是作爲一個空數組'[]'提供的。這是否回答你的問題? – paulpdaniels