简体   繁体   中英

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. 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. 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

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中进行设置来解决了此问题(并没有真正解决,但找到了另一个解决方案)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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