以下是我的情景:
endDateLong
确定)orderByChild
我的解决方案(设计):
我的工作代码:
这种递归函数运行良好且很好,并且可以达到目的。
fetchFilteredEvents(startKey:number) {
let self = this;
let cacheKey = this.fireRoute.getPathForMetaEvents();
let evListObs:FirebaseListObservable<Event[]>;
evListObs = self.db.list(cacheKey, {
query : {
orderByChild : 'endDateLong',
startAt : startKey,
limitToFirst : 50
}
});
return evListObs.first().map(evList => {
let cList = evList.filter(ev => {
/**
* BEGIN: Check if event falls in any Preferred locations
*/
let allBlocks = self.volService.me.locationPreferences.blocks;
let prefBlockIDs= Object.keys(allBlocks)
.filter(b => { return allBlocks[b] });
let matchingObj = prefBlockIDs.find( bid => { return bid == ev.block.id } );
// return true, if any matching block is found
if (matchingObj) return true;
/**
* END: Check if event falls in any Preferred locations
*/
return false;
});
self.eventCount += cList.length;
// If required 30 items are retrieved or event list is exhausted just return current list.
// If not, recursively call the function again with timestampe of the last event and append it's return value to current array and return the whole appended list
if (evList.length == 1 || self.eventCount > 30) {
return cList;
} else {
let lastEvent = evList[evList.length -1];
console.log("Fetch next page @ ", lastEvent.endDate);
console.log("Current list is ", cList);
return self.fetchFilteredEvents(lastEvent.endDateLong).then(allEvents => {
return allEvents.concat(cList);
});
}
}).toPromise();
}
此代码出现问题:
我想要的: 我想通过observables以某种方式改进代码:
PS:它的Angular 2(或4)代码和AngularFire2
任何指针?
更新1 - 转换为Observables(没什么)
private fetchFilteredEvents(startKey:number) : Observable<Event[]> {
let that = this;
let cacheKey = this.fireRoute.getPathForMetaEvents();
let evObs = that.db.list(cacheKey, {
query : {
orderByChild : 'endDateLong',
startAt : startKey,
limitToFirst : 10
}
}).map(evList => {
let cList = evList.filter(ev => {
// Filter logic goes here
});
that.eventCount += cList.length;
// If required 30 items are retrieved or event list is exhausted just return current list.
// If not, recursively call the function again with timestampe of the last event and append it's return value to current array and return the whole appended list
if (evList.length == 1 || that.eventCount > 30) {
return cList;
} else {
let lastEvent = evList[evList.length -1];
console.log("Fetch next page @ ", lastEvent.endDate);
console.log("Current list is ", cList);
// THIS IS NOT WORKING. I am only getting the first 10 events. I think I should somehow merge the returning obserable of recursive calls to `that.fetchFilteredEvents()` to `evObs`, rather than array merging as done here.
return that.fetchFilteredEvents(lastEvent.endDateLong).subscribe(nextList => {
console.log(nextList);
cList = cList.concat(nextList);
return cList;
});
}
});
this.currentList = evObs;
return this.currentList;