javascript - 角度存储检查失败
问题描述
我将数据存储在我的 localStorage 中,并在我的组件中OnInit
检查该数据是否存在过滤表结果,如果不存在,则显示所有结果。
问题是此功能有时有效,有时无效!我不确定是什么原因导致了这个问题,但是当我硬刷新我的页面时最容易失败Ctrl+F5
代码commented
searchbar_values: boolean = false;
tableSearch_column: boolean = false;
ngOnInit(): void {
// Get all data from server
this.getList(null);
// Condition 1 (first storage values)
const getstoredata = store.get('searchbar_values')
if (getstoredata) {
this.searchbar_values = true;
this.tableSearch_column = false;
}
// Condition 2 (second storage values)
const getstoredata2 = store.get('tableSearch_column')
if (getstoredata2) {
this.tableSearch_column = true;
this.searchbar_values = false;
}
// if first condition happened do this (sometimes fail)
if (this.searchbar_values) {
const storeData = store.get('searchbar_values')
this.globalSearchService.searchTerm.next(storeData.value);
this.globalSearchService.searchTerm.subscribe((newValue: string) => {
this.searchTerm = newValue;
if (newValue != null) {
this.visible = false;
this.globalSearchService.getSearchBar(newValue).subscribe((data: any) => {
this.listOfData = data.data;
this.limit = data.limit
this.totalPages = data.total
this.page = data.page
this.pages = data.pages
this.isSpinning = false;
store.set('searchbar_values', { value: newValue })
this.searchbar_values = true;
if (this.tableSearch_column) {
store.remove('tableSearch_column');
this.tableSearch_column = false;
}
});
}
});
}
// if second condition happened do this (sometimes fail)
if (this.tableSearch_column) {
const storeData = store.get('tableSearch_column')
this.isSpinning = true;
this.globalSearchService.getTableFilter(storeData.field, storeData.op, 'none', storeData.value).subscribe((data: any) => {
this.listOfData = [];
this.listOfData = data.data;
this.limit = data.limit
this.totalPages = data.total
this.page = data.page
this.pages = data.pages
this.isSpinning = false;
});
}
}
PS: tableSearch_column
并且searchbar_values
永远不会同时存储在 localStorage 中,因为我总是在存储另一个之前删除一个。
所以逻辑是其中之一存在或都不存在。
任何想法?
解决方案
解决了
我已将存储检查移至constructor
如下:
constructor(
//....
) {
//...
const getstoredata = store.get('searchbar_values')
if (getstoredata) {
this.searchbar_values = true;
this.tableSearch_column = false;
}
const getstoredata2 = store.get('tableSearch_column')
if (getstoredata2) {
this.tableSearch_column = true;
this.searchbar_values = false;
}
}
ngOnInit
然后像你在我上面的问题中看到的那样调用我的条件。现在每次调用 localStorage 并返回正确的值。
推荐阅读
- node.js - nodejs pdf解析在特定字符串后获取值
- svg - svg - 拐角不像预期的那样锋利
- javascript - node.js express 和正则表达式
- python - 输入1个数字后如何使代码不结束?
- python - 从较大的给定边界创建一组连续的非重叠边界
- javascript - 无法读取类组件中的历史记录
- php - woocommerce - 删除我帐户中的“查看订单”按钮
- node.js - Socket.IO cors 问题无法用以前的 SO 答案解决
- nosql - 如何在 Oracle NoSQL 数据库云服务中创建混合表?
- android - 我们应该为我们的两个 gradle 任务创建一个 firbase json 文件吗?