【问题标题】:How to use set timeout using redux如何使用 redux 设置超时
【发布时间】:2019-04-05 15:08:01
【问题描述】:

我必须在令牌到期时间 5 分钟之前显示警报消息。 我已经尝试过这个解决方案。

showTokenExpiryAlert() {
    /* Convert expiresIn (seconds) to expiresIn (miliseconds) */
    const expiresIn = this.expiresIn * 1000;

    /* calculate alert time from expiresIn (miliseconds) */
    const alertTime = expiresIn - 300000;

    /* Show alert message before 5 mins of token expiry time */
    setTimeout(() => {
      alert('Token will be exppired soon');
    }, alertTime);
  }

此代码运行良好。但是,它在页面刷新时失败。所以,我正在考虑使用 redux,但没有得到确切的解决方案如何使用 redux。

【问题讨论】:

  • 你得到什么错误?
  • 尝试将alertTime放入sessionStorage或localstorage。它可能会对你有所帮助。
  • 没有错误....但是我在登录页面上使用了这个 settimeout。所以,当我访问另一个页面并刷新它时,settimeout 不起作用。

标签: angular redux settimeout


【解决方案1】:

假设你使用 ngrx 作为 Angular 的 Redux 实现:

  1. 默认情况下,ngrx/store 将所有状态保存在内存中,因此在全页重新加载时,您无论如何都会丢失整个应用程序状态,即使使用 redux。
  2. 您可以尝试save whole ngrx app state in localStorage,但如果您只需要检查令牌是否已过期,那将是一项更广泛的任务

所以最好按照@Aarsh 上面的建议去做。

创建服务:

  1. 在 localStorage 中存储过期时间并启动计时器
  2. 在应用程序启动(页面重新加载)时从 localStorage 重新读取过期时间,如果过期时间已经存在,则重新启动计时器

【讨论】:

    【解决方案2】:

    您应该做的第一件事是将过期警报的显示逻辑移动到始终存在的组件中(例如header-component),但仅在成功登录后才激活。您的登录组件在成功登录后在 localStorage 中设置过期时间并设置一个标志,以便可以初始化 headerComponent。您的标头组件从 localStorage 读取值并启动计时器。

    showTokenExpiryAlert() {
        /* Convert expiresIn (seconds) to expiresIn (miliseconds) */
        const expiresIn = localStorage.getItem('expiresIn') * 1000;
    
        /* calculate alert time from expiresIn (miliseconds) */
        const alertTime = expiresIn - 300000;
    
        if (alertTime > 0) {
            /* Only show the alert if the token hasn't already expired */
            setTimeout(() => {
              alert('Token will be exppired soon');
            }, alertTime);
        }
        else {
           localStorage.removeItem('expiresIn');  // token already expired
           // navigate to login
        }
      }
    

    不要使用 SessionStorage 而不是 localStorage,这将在浏览器关闭时被清除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2012-01-08
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多