简体   繁体   English

localStorage中的JWT仅在刷新页面后才能工作

[英]JWT in localStorage only works after refreshing the page

So I am working on an angular2 application and am trying to generate a JWT after logging in so that a user's profile information can be obtained. 因此,我正在研究angular2应用程序,并尝试在登录后生成JWT,以便可以获取用户的个人资料信息。 I can successfully login and that's when I generate the token. 我可以成功登录,这就是我生成令牌的时间。 After logging in I route the user to the profile page and that's where I call my api to get the user information. 登录后,我将用户引导到个人资料页面,这就是我调用api来获取用户信息的地方。 All of this only works after I login and refresh to page. 所有这些仅在我登录并刷新到页面后才起作用。

this.auth_service
      .Login(this.email, this.password)
      .subscribe(
              data => {
                         this.global_events.change_nav_bar.emit(true)
                         console.log('logged in successfully: ' + data)
                         this.router.navigate(['/profile'])
                     })

// auth_service above calls this method //上面的auth_service调用此方法

Login(email, password): Observable<boolean>
    {
        return this.http
                    .post('/api/login', JSON.stringify({email: email, password: password}), this.Get_Headers('no_auth'))
                    .map(Handle_Response)

        function Handle_Response(response: Response)
        {
            let token = response.json() && response.json().token
            if(token)
            {
                this.token = token
                localStorage.setItem('current_user', JSON.stringify({ email: email, token: token }))
                return true
            }
            else
                return false
        }
    }

// Then in my profile component I do this. //然后在我的个人资料组件中执行此操作。 I have experimented with different timeout times. 我尝试了不同的超时时间。

ngOnInit(): void
    {
        this.global_events.change_nav_bar.emit(true)

        setTimeout(() => this.Get_User_Data(), 10000)
    }

我通过直接从localStorage提取令牌而不是在authenticationService中进行设置来解决了此问题(并没有真正解决,但找到了另一个解决方案)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM