1.先不做上拉触发,用button模拟一下,触发函数
export class StudyComponent implements OnInit { /*列表数据流 */
list$: Observable<any[]>;
/*页面缓存*/
beh: BehaviorSubject<any[]>;
/*模拟下拉事件 */
scrolEvent = new Subject(); ngOnInit() {
/*订阅scrolEvent,下方scrol()执行next的时候会跑这个订阅 */
this.scrolEvent.pipe(
map(() => {
this.getdata();
})
).subscribe();
} constructor() {
this.list$ = new Observable<any[]>();
this.beh = new BehaviorSubject<any[]>([]);
} /*获取数据 */
getdata() {
this.list$ = this.beh; // 提供观察者next新数据
const oldlist = this.beh.getValue(); // 取旧数据
this.serve()
.subscribe(v => {
this.beh.next(oldlist.concat(v));
});
} /*滚动触发函数 */
scrol() {
this.scrolEvent.next();
} /*模拟接口返回数据 */
serve() {
return of([Math.random() * , Math.random() * , Math.random()]);
}
}
html
<ng-container *ngIf="list$ | async as list">
<div>
<p *ngFor="let item of list">{{item}}</p>
</div>
</ng-container> <button (click)="scrol()">列表</button>
2.若是有两个列表(像顶部tab有 待处理、全部)
export class StudyComponent implements OnInit { /*列表数据流 */
list$: Observable<any[]>;
/*模拟下拉事件 */
scrolEvent = new Subject();
/*两个页面数据 缓存*/
segData: {
flag1: BehaviorSubject<any[]>,
flag2: BehaviorSubject<any[]>
};
/*当前页标签 默认页面1*/
curFlag = 'flag1'; ngOnInit() {
this.list$ = new Observable<any[]>();
// this.segData.flag1 = new BehaviorSubject<any[]>([]);
// this.segData.flag2 = new BehaviorSubject<any[]>([]);
this.segData = {
flag1: new BehaviorSubject<any[]>([]),
flag2: new BehaviorSubject<any[]>([])
}; /*订阅scrolEvent,下方scrol()执行next的时候会跑这个订阅 */
this.scrolEvent.pipe(
map(() => {
this.getdata(this.curFlag);
})
).subscribe();
} constructor() {
} /*获取数据 */
getdata(flag: string) {
this.list$ = this.segData[flag]; // list$指向一个segData
const oldlist = this.segData[flag].getValue(); // 取旧数据
this.serve(this.curFlag)
.subscribe(v => {
this.segData[flag].next(oldlist.concat(v));
});
} /*滚动触发函数 */
scrol(flag: string) {
this.curFlag = flag;
this.scrolEvent.next();
} /*模拟接口返回数据 */
serve(flag: string) {
return of(
[
Math.random() * + flag,
Math.random() * + flag,
Math.random() + flag]
);
}
}
html
<ng-container *ngIf="list$ | async as list">
<div>
<p *ngFor="let item of list">{{item}}</p>
</div>
</ng-container> <button (click)="scrol('flag1')">列表1</button>
<button (click)="scrol('flag2')">列表2</button>