Cannot read Property 'token' of Undefined when receiving angular localstorage object

Asked

Viewed 85 times

0

My login function keeps on localstorage a token returned from the api:

  localStorage.setItem('token', res.data.token);

Right after logging in, I need to pass this token to another function, but I can’t get my variable to receive the token saved on localstorage, tried something like:

ngOnInit() {
    let token = localStorage.getItem('token')
    this.trocaToken(token);
}

But I do get:

Cannot read Property 'token' of Undefined

If I give a console.log(localStorage.getItem('token'), it normally prints my token, but I can’t get it into a variable.

1 answer

0

You need to declare the variable localstorage before. To follow an example:

import { LocalStorageService } from 'ngx-webstorage';

export class LoginComponent implements OnInit {

    credenciais: any;
    lembrarCredenciais: boolean;

    constructor(
        private localStorage: LocalStorageService
    ) {
        const loginGravado = localStorage.retrieve('credenciais');

        this.lembrarCredenciais = !!loginGravado;
        this.credenciais = Object.assign({}, {
            login: '',
            senha: ''
        }, loginGravado);
    }

    async fazerLogin() {
        try {
            this.form.validate();

            if (this.lembrarCredenciais) {
                this.localStorage.store('credenciais', this.credenciais);
            }
    // ...

}

Ngx-webstorage has been downloaded from npmjs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.