我是否需要刷新页面才能获取用户数据?

时间:2019-11-05 00:32:43

标签: node.js angular

现在我必须刷新页面才能从本地存储中获取用户数据,但我不确定这是否是正确的处理方式。我将如何获取登录时的用户数据?现在,我只是从本地存储JWT中获取它,但这似乎不是最佳实践。我应该在每次登录时根据他们的ID来获取用户吗?我该如何保存这些数据?

reload(){
    this.router.navigate(['/']);
  }

login(userName: string, email: string, password: string) {
    const authData: LoginData = {userName, email, password };
    console.log('AuthData', authData);
    this.http.post<{token: string, expiresIn: number, displayName: string}>(this.loginRoute, authData)
      .subscribe(response => {
        const token = response.token;
        this.token = token;
        if (token) {
          const expiresInDuration = response.expiresIn;
          this.setAuthTimer(expiresInDuration);
          this.isAuthenticated = true;
          this.username = response.displayName;
          this.authStatus.next(true);
          const now = new Date();
          const expirationDate = new Date(now.getTime() + expiresInDuration * 1000);
          console.log(expirationDate);
          this.saveAuthData(token, expirationDate, userName);
          this.reload();
        }
      });
  }

我希望能够在当前登录用户的主页上显示用户数据,但不确定如何保留该数据。现在我只是在使用本地存储。

1 个答案:

答案 0 :(得分:0)

没有后端,您没有很多选择(例如websocket)。但是,有了您所拥有的功能,您可以从登录创建一个单独的功能,该功能检查用户是否已通过身份验证,并将其间隔一定时间,然后每X秒轮询一次。这将摆脱重载功能。您将创建一个Observable onInit,它每隔10秒就会关闭一次,或者检查令牌的状态。

干杯!