angular - localStorage 值被分页器 NaN 清除
问题描述
我有一个名为的函数onPageChange
,它将 currentPage 存储在 localStorage 中,这部分可以工作,但是如果我重新加载页面,那么它会清除 localStorage 中的值。我添加了一个警报,如果我单击第 4 页并重新加载,它将显示。CURRENT PAGE IS 4
,但在页面完全加载后,从中检索 4 的值被替换为 NaN。我怎样才能阻止这种情况发生?目标是返回组件并加载它们所在的最后一页。当用户登录时,我将 localStorage 值设置为第 1 页以重置它。
currentPage;
ngOnInit() {
this.currentPage = parseInt(localStorage.getItem("currentPage"));
alert("CURRENT PAGE IS: " + this.currentPage);
this.userId = this.authService.getUserId();
this.isLoading = true;
this.spinner.show();
const postsPerPage = 10;
let listingRoute = "main";
this.submitListingService
.getListings(false, false, listingRoute, postsPerPage, this.currentPage, null)
.pipe(takeUntil(this.destroy))
.subscribe(postData => {
this.isLoading = false;
this.totalPosts = postData.maxPosts;
console.log(this.totalPosts);
console.log(postData);
this.posts = postData.posts;
this.posts1 = postData.posts;
this.posts3 = postData.posts;
this.filteredPosts = postData.posts;
});
}
onPageChange(currentPage: PageEvent) {
let counter: number;
counter = 0;
counter++;
localStorage.setItem("currentPage", currentPage.toString());
let newPage: number;
newPage = parseInt(currentPage.toString());
const postsPerPage = 10;
console.log("currentPAGE" + newPage);
if (this.filtersEnabled) {
let listingRoute = "filter";
this.submitListingService
.getListings(
this.buyItNowEnabled,
this.privateAuctionEnabled,
listingRoute,
postsPerPage,
newPage,
null
)
.pipe(takeUntil(this.destroy))
.subscribe(postData => {
this.isLoading = false;
if (!this.isLoading) {
this.totalPosts = postData.maxPosts;
console.log(this.totalPosts);
this.isLoading = true;
this.posts = postData.posts;
this.posts1 = postData.posts;
window.scroll(0, 0);
this.posts3 = postData.posts;
this.filteredPosts = postData.posts;
localStorage.setItem("currentPage", newPage.toString());
}
});
} else if (!this.filtersEnabled) {
let listingRoute = "main";
this.submitListingService
.getListings(false, false, listingRoute, postsPerPage, newPage, null)
.pipe(takeUntil(this.destroy))
.subscribe(postData => {
this.isLoading = false;
this.totalPosts = postData.maxPosts;
console.log(this.totalPosts);
this.isLoading = true;
this.posts = postData.posts;
this.posts1 = postData.posts;
window.scroll(0, 0);
this.posts3 = postData.posts;
this.filteredPosts = postData.posts;
});
}
}
分页器
<ngb-pagination (pageChange)="onPageChange($event)" [collectionSize]="this.totalPosts" *ngIf="!this.mobile"
[(page)]="this.currentPage" [boundaryLinks]="true"></ngb-pagination>
解决方案
推荐阅读
- objective-c - Final cut pro 自定义共享到我的未响应的可编写脚本的应用程序
- docker - Docker 上的 JavaFX - 初始化 QuantumRenderer 时出错:找不到合适的管道
- javascript - HTML 2d 画布作为 webgl 画布上的纹理
- r - 使用 R 语言为 arima 生成示例路径
- ios - 如何使用联系人 UI 快速打开现有联系人的编辑联系人 UI
- windows - 批处理文件 - 设置参数值,然后传递给 exe
- r - 在 R rethinking 包中,嵌套索引的语法是什么?
- apache-kafka - 如何增加卡夫卡消费者没有
- android - 刷卡时关闭卡片视图
- java - Java 正则表达式仅返回单个匹配项