angularjs 如何在angular js中自动过期本地存储值?

laximzn5  于 2023-08-02  发布在  Angular
关注(0)|答案(4)|浏览(132)

我在应用程序中使用localStorage。我想在20分钟后清除这些值。你能帮帮我吗?

o75abkj4

o75abkj41#

我为angular-localStorage编写了一个扩展(https://github.com/grevory/angular-local-storage),当您在set方法中提供可选参数时,它能够自动删除localStorage中的条目。
https://gist.github.com/Kyoss79/8cd37a54679804fdeb6d

mznpcxlj

mznpcxlj2#

在引导你的模块调用后,运行并设置一个$interval,在20分钟后清除本地存储。

app.run(function($interval){
  $interval(() => {
    delete localStorage[key]
    // delete all the required localStorage variables by specifying their keys
  }, 1000*60*20)
})

字符串

lf5gs5x2

lf5gs5x23#

根据W3Schools:
localStorage对象存储没有到期日期的数据。当浏览器关闭时,这些数据不会被删除,并且将在第二天、第二周或第二年可用。
然而,类似的问题已经在其他地方提出并得到了回答:When do items in HTML5 local storage expire?这里提到了一些可能对您有用的变通方法。

ki0zmccv

ki0zmccv4#

您可以在一个缓存服务或本地存储服务中拥有自定义的通用实现。这是我的工作。

import { Injectable } from '@angular/core';
// using ionic angular storage
import { Storage } from '@ionic/storage-angular'; 

export class CachedItem<T> {
  public _value: T | undefined;
  public _expiry: any;

  constructor(private name: string) { }

  public setValue(value: T) {
    this._value = value;
    this._expiry = new Date().getTime() + 1800000; // 30 mins 
  }
}

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {
  private _storage: Storage | null = null;

  constructor(private storage: Storage) {
  }

  async init() {
    const storage = await this.storage.create();
    this._storage = storage;
  }
 
  private async CheckStorage() {
    if (!this._storage) {
      this._storage = await this.storage.create();
    }
  } 

  // Generic cache with expiry 
  public async setCache<T>(key: string, items: T) {
    let cachedItem = new CachedItem<T>(key);
    cachedItem.setValue(items);

    await this.CheckStorage();
    return await this._storage?.set(key, cachedItem);
  }

  public async getCache<T>(key: string) {
    await this.CheckStorage();
    const cashedItem: CachedItem<T> = await this._storage?.get(key);
    if (cashedItem !== null) {
      if (new Date().getTime() > cashedItem._expiry) {
        // If the item is expired, delete the item from storage  and return null
        await this._storage?.remove(key);
        return null
      }
      return cashedItem._value as T;
    }

    return null;
  }

}

字符串
你可以像下面这样使用

async loadData() {

    // gets the cache
    var datas: MyDataType[] = await this.localStorageService.getCache('datacachekey');
    if (datas == null) { // not available in the cache, go fetch and put into the cache
      
      this.myDataService.getDatasFromApi().subscribe(
        (myData) => {
          // sets the cache
          await this.localStorageService.setCache('datacachekey', myData); 

          // work on the data 
        },
        () => {
          //error;
        }
      );

    }
    else {
       // work on the data as received from cache
    }
  }

相关问题