nas
nas

Reputation: 2437

localstorage value visible only after page reload

When the user login I want to display the username of that user at the navbar. I have set the token and username to the localStorage after user succesfully login. My issue is username is not displayed at the navbar unless I refresh the page.

I am not sure how can I fix this problem.

Can anybody help me

Thank You.

login component

onSubmit = function () {
        this.userService.loginUser(this.loginUserData).subscribe(
            res => {
                this.tokenService.handle(res);
                this.authService.changeAuthStatus(true);
            },
            error => console.log(error)
        );
    }

auth service

export class AuthService {

    private loggedIn = new BehaviorSubject<boolean>(this._tokenService.loggedIn());
    authStatus = this.loggedIn.asObservable();
    user = this.tokenService.getUser();

    changeAuthStatus(value: boolean) {
        this.loggedIn.next(value);
    }

    constructor(private tokenService: TokenService) {}
}

token service

handle(res) {
        this.setToken(res);
    }

    setToken(res) {
        localStorage.setItem('token', res.access_token);
        localStorage.setItem('user', res.user);
    }

    getToken() {
        return localStorage.getItem('token');
    }

    getUser() {
        return localStorage.getItem('user');
    }
}

navbar component

ngOnInit() {
    this.authService.authStatus
        .subscribe(
            value => {
                this.loggedIn = value
            }
        );
    //set the username on navbar
    this.user = this.tokenService.getUser();
}

Upvotes: 0

Views: 81

Answers (2)

Minu
Minu

Reputation: 242

Try making the call

this.user = this.tokenService.getIser() 

inside the subscribe.

Upvotes: 1

Ahsan Sohail
Ahsan Sohail

Reputation: 670

You auth service function is a callback that will fire success or failure event when all operations are complete hence the code this.user = this.tokenService.getUser(); executed before the localstorage is populated. Try moving this code inside subscribe method of authService.authStatus.

ngOnInit() {
    this.authService.authStatus
        .subscribe(
            value => {
                this.loggedIn = value
            }
        );
    //set the username on navbar
    this.user = this.tokenService.getUser();
}

like this.

ngOnInit() {
    this.authService.authStatus
        .subscribe(
            value => {
                this.loggedIn = value
                this.user = this.tokenService.getUser();

            }
        );
}

Upvotes: 1

Related Questions