2016-02-26 36 views
2

這是一個基本的rxjs問題,我無法找到答案。說我讓一個可觀察的字符串,然後經過一段時間,我想給它分配一個新的值。新值似乎沒有被觀察到,因爲它沒有被記錄。我知道rx正在工作,因爲初始值被記錄爲一系列字符。你能解釋一下我做錯了什麼,以及爲了能夠記錄這個新值,我需要修改什麼?在這裏,我使用setTimeout函數來更新變量,但實際上它將是一個返回保存該值的JSON對象的ajax請求。訂閱從字符串Rx.Observable無法處理值賦值

var observableId = "hwebd788ew98ew9"; 

var sourceAid = Rx.Observable.from(observableId); 
var subscriptionAid = sourceAid.subscribe(

function (x) { 
    console.log('changed!', x); 
}, 
function (err) { 
    console.log('Error: ' + err); 
}, 
function() { 
    console.log('Completed'); 
}); 


setTimeout(function() {  
    observableId = "yrth5yu56uy56"; 
}, 2000); 

回答

0

這裏是將數據推到一個數組

var first = []; 

var s1 = new Rx.Subject(); 

s1.subscribe(first.push.bind(first)); 

s1.onNext('I'); 
s1.onNext('am'); 

setTimeout(function() {  
    s1.onNext('late'); 
    console.log('late',first); 
}, 2000); 

console.log('first'first); 

的例子,如果你運行你會得到

"first" 
["I", "am"] 
"late" 
["I", "am", "late"] 

我希望幫助

0

首先,其原因爲什麼「初始值被記錄爲級聯字符」是因爲Observable.from接受迭代器作爲參數。因此,當你傳遞一個字符串時:它被視爲一個數組,並且每個字符都成爲一個迭代器,其結果是每個字符一次記錄一次。

最簡單的方法來創建一個可觀察的是

  1. 的初始值。
  2. 能有傳入更多的價值隨着時間的推移

是使用BehaviorSubject:

var stream = new Rx.BehaviorSubject('test0'); 
 

 
stream.subscribe(hash => console.log(hash)); 
 
var testCount = 0; 
 

 
setInterval(() => stream.next(`test${++testCount}`, 5000));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.3/Rx.min.js"></script>

如果你想通過這個觀察到了另一個類或函數,並且不希望他們能夠在您的BehaviorSubject上調用next,您可以使用asObservable方法將它們傳遞給可觀察對象:

return stream.asObservable(); 

現在您可以不斷更新您的BehaviorSubject,並且消費者將只能訂閱事件,但不能創建新事件。

-1

您需要執行Observable.next()將數據推送到所有訂閱的方法。

讓我解釋一下你的問題

//this is a normal variable. updating anything will not effect observable 
var observableId = "hwebd788ew98ew9"; 

//sourceAid will be an observable and the intitial value will be observableId 
var sourceAid = Rx.Observable.from(observableId); 

// you are subscribing the value which is good. 
var subscriptionAid = sourceAid.subscribe(

function (x) { 
    console.log('changed!', x); 
}, 
function (err) { 
    console.log('Error: ' + err); 
}, 
function() { 
    console.log('Completed'); 
}); 

// here youa re changing observableId which is normal javascript veriable and it has nothing to do with observable 
setTimeout(function() {  
    observableId = "yrth5yu56uy56"; 
}, 2000); 

// you need to eimt/change/add value to 'sourceAid' as it is subscribed and responsible to notify all methods subscribing it for updates. 

//this will update 
sourceAid.next("yrth5yu56uy56") 
+0

您的代碼不工作,(https://runkit.com/embed/2jmrvfbv9u27)......因爲'Observable's沒有'。下一個'方法。 'Observer'確實有'.next'方法。這就是爲什麼你會使用'Observer'和'Observable'這兩個'Subject'或'BehaviorSubject'。 – dovidweisz

+0

runit不可編輯。由於您的sourceAid已訂閱,因此需要更新。不是可觀察的ID。 –

+0

頁面底部有一個「克隆和編輯」按鈕? – dovidweisz