如何使用 redux 设置超时

How to use set timeout using redux

我必须在令牌到期时间 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 的确切解决方案。

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

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

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

创建服务:

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

您应该做的第一件事是将过期警报的显示逻辑移动到一个始终存在(例如 header-component)但仅在成功登录后激活的组件中。您的登录组件在成功登录后在 localStorage 中设置过期时间,并设置一个标志,以便 headerComponent 可以被初始化。您的 header 组件从 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,它会在浏览器关闭时被清除。