首页 > 解决方案 > 角度存储检查失败

问题描述

我将数据存储在我的 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 中,因为我总是在存储另一个之前删除一个。

所以逻辑是其中之一存在或都不存在。

任何想法?

标签: javascriptangulartypescript

解决方案


解决了

我已将存储检查移至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 并返回正确的值。


推荐阅读