import { Component, OnInit, Input, Output,EventEmitter } from '@angular/core'; import { List } from '../service/list'; /*interface LoadOption { remote?:Function, perPage?:number }*/ import { BaseLog as Log } from "base-log"; const log = new Log('ListLoadComponent'); @Component({ selector: 'list-load', template: ` ` }) export class ListLoadComponent implements OnInit { _listData @Input() option @Output() listDataChange = new EventEmitter() @Input() get listData(){ return this._listData; } set listData(val){ this._listData = val this.listDataChange.emit(val); } canBeLoaded = true; current max timer remote infiniteScroll data constructor(public list:List) { } ngOnInit() { } ngAfterViewInit(){ const { perPage, remote } = Object.assign({},this.option); this.remote = remote; this.data = this.list.set(this._listData, perPage); this.initLoad(); } // 初始化load initLoad = () => { const listData = this.data.all(); this.max = this.getMax(this.data); this.current = this.getCurrent(listData, this.data); // 当前页码 this.canBeLoaded = true; } // 加载更多 loadMoreData = (infiniteScroll) => { log.info('infiniteScroll',!!infiniteScroll); this.infiniteScroll = infiniteScroll; if(this.current == this.max){ if(this.remote){ // 远程更新,添加数据 return this.remote(this.data,this.option).then((res) => { res = res || []; if(res.length == 0) return this.finishUpdate(); this.data.add(res); // 将新数据添加到data中 this.max = this.getMax(this.data); // 重新计算max if(this.max > this.current){ return this.update(); }else{ return this.finishUpdate(); } }); }else{ return this.finishUpdate(); } }else{ // 本地更新 return new Promise((resolve) => { this.timer = setTimeout(()=>{ const current = this.update(); resolve(current); },360); }) } } // 获取最大页码 getMax = (data) => { return data.count() / data.perPage; } // 获取当前页码 getCurrent = (listData,data) => { return listData.length / data.perPage; } // 更新数据 update = () => { const listData = this.data.getPageDataAll(this.current + 1); this.infiniteScroll.complete(); // 关闭loading this.current = this.getCurrent(listData, this.data); this._listData = listData; this.listDataChange.emit(listData); return listData; } // 结束更新 finishUpdate = () => { this.canBeLoaded = false; clearTimeout(this.timer); } }