如何使用rxjs解决这个特定场景?

时间:2016-10-03 11:38:55

标签: angular rxjs

问题我有一个可以便宜加载的id列表,每个加载详细信息都比较贵。

所以我想加载'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

1 个答案:

答案 0 :(得分:1)

如果您只想使用observable,可以按照以下步骤进行操作

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