2016-08-15 24 views
3

我正在編碼Typescript 1.9並使用RxJS 5。我試圖構建一個只能發射一個值的可觀測值:true如果任何內部的Observable<number>的發射屬於固定的數字陣列。否則爲false。這是我的代碼:RxJS 5可觀察:是否有任何結果屬於已知集合

let lookFor = [2,7]; // Values to look for are known 
Observable.from([1,2,3,4,5]) //inner observable emits these dynamic values 
    .first(//find first value to meet the requirement below 
     (d:number) => lookFor.find(id=>id===d)!==undefined, 
     ()=>true //projection function. What to emit when a match is found 
    ) 
    .subscribe(
     res => console.log('Result: ',res), 
     err => console.error(err), 
     () => console.log('Complete') 
    ); 

上面的代碼很好用。它將輸出繼電器:

結果:真實的(因爲內部觀察到發射2,這是在lookFor

完全發現

如果我開始Observable.from([8,9])我想獲得Result: false因爲有與lookFor沒有重疊,而是錯誤處理程序被觸發:

Object {name:「Empty E RROR」,棧:‘’}

什麼讓我觀察到的要儘快找到一個匹配發出true正確的方法,但發出false如果仍然沒有匹配在流的結束?

回答

1

沒有讓你指定的缺省值使用,如果沒有找到匹配的附加參數:

... 
.first(//find first value to meet the requirement below 
    (d:number) => lookFor.find(id=>id===d)!==undefined, 
    ()=>true, //projection function. What to emit when a match is found 
    false //default value to emit if no match is found 
) 
...