Sean Paul
Sean Paul

Reputation: 85

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)
    }

Upvotes: 0

Views: 1626

Answers (1)

Sean Paul
Sean Paul

Reputation: 85

I solved this (not really solved but found another solution) by just pulling the token directly from localStorage instead of setting in the authenticationService

Upvotes: 1

Related Questions