rxjs的switchMap
// 然而rxjs只能解决请求竞态的问题,如果在请求期间修改了listdata数据源(如下所示读取了缓存),那么页面结果展示依然是错误的
// 最好的方法是对页面操作施加锁,一旦在请求,不能切tab
getList$ = new Subject();
@Watch('filters', { deep: true, immediate: true })
async resetFilters(filter: any) {
const { startDate, endDate } = filter;
// 有缓存读缓存
if (this.timeMap[`${startDate}${endDate}`]) {
this.listData = this.timeMap[`${startDate}${endDate}`].list;
this.finish = this.timeMap[`${startDate}${endDate}`].finish;
this.page = this.timeMap[`${startDate}${endDate}`].page;
return;
}
if (!this.activatedFlag || startDate === endDate) return;
// 从头开始获取列表
this.finish = false;
this.page = 0;
this.listData = [];
this.loadMore();
}
public loadMoreInit() {
this.getList$
.pipe(
switchMap(() => {
return this.getList();
})
)
.subscribe(
({ items: newData, paginator: { page, pageSize, totalCount } }) => {
const { startDate, endDate } = this.filters;
this.loading = false;
if (page * pageSize >= totalCount) {
this.finish = true;
}
this.listData = this.listData.concat(newData) as [];
this.timeMap[`${startDate}${endDate}`] = {
page: this.page,
finish: this.finish,
list: this.listData,
};
}
);
}
public getList() {
return this.getListData({
page: this.page,
pageSize: 10,
...this.filters,
});
}
public async loadMore() {
if (this.finish) {
return;
}
this.page += 1;
this.loading = true;
this.getList$.next({});
}
cancelToken
import axios from 'axios';
const { CancelToken } = axios;
data() {
return {
cancelRequest: null, // 初始时没有请求需要取消,设为null
};
},
getListData(filter) {
if (typeof this.cancelRequest === 'function') {
this.cancelRequest();
}
return api.getListNewMemberRankPaged(
filter,
// 第二个参数传到底层的axios的options中
new CancelToken(function executor(c) {
this.cancelRequest = c;
})
);
},
版权声明:本文为radation原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。