2016-10-03 64 views
0

問題我有一個ID列表,我可以加載便宜,爲每個加載細節更昂貴。我如何使用rxjs解決這個特定的場景?

所以我想加載'id對象'的整個列表,訂閱流獲取前5,並在鼠標點擊獲取下5(分頁來回)。

生成的流然後會爲當前批次中的每個項目發出xhr請求。

var clicks = Rx.Observable.fromEvent($nextPageButton, 'click') 
var arrayObs = Observable.from([{id:3}, {id:2}, {id:1}, {id:6}, {id:5}, {id:4}]); 

我已經嘗試過無數的映射合併等方式。不能獲得它的竅門。

簡單plunker

https://plnkr.co/edit/W83d3xftZv25YqhOF8uL?p=preview

+0

可以ü請進一步提供plunkr鏈接/代碼的細節 –

回答

1

如果你只想使用觀測,你可以做如下

let page = 0; 
let size = 3; 

let arrayObs = Observable.from([{id:3}, {id:2}, {id:1}, {id:6}, {id:5}, {id:4}]); 

// Click observables that emit the page we want to display. 
let clickPreviousObs = Observable.fromEvent(this.prevButton.nativeElement, 'click').map(() => { 
    page--; 
    return page; 
}); 
let clickNextObs = Observable.fromEvent(this.nextButton.nativeElement, 'click').map(() => { 
    page++; 
    return page; 
}); 

// Merge click observables so there is only one observable that emit the page, and start with the first page. 
let pageObs = Observable.merge(clickPreviousObs, clickNextObs).startWith(page); 

// When I get a new page, get the corresponding ids. 
let resultObs = pageObs.flatMap((currentPage) => { 
    console.log('Page ', currentPage); 
    return arrayObs.skip(currentPage * size).take(size); 
}); 

resultObs.subscribe((res) => { 
    console.log('Result', res); 
}); 

plunkr