Can not read property 'token' of undefined when receiving object from angular localstorage

0

My login function stores a token returned from api in localstorage :

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

Soon after logging in, I need to pass this token to another function, but I can not get my variable to receive the token stored in localstorage , I tried something like:

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

However, I get:

  

Can not read property 'token' of undefined

If I give a console.log(localStorage.getItem('token') , it usually prints my token, but I can not put it inside a variable.

    
asked by anonymous 23.07.2018 / 18:29

1 answer

0

You need to declare the variable localstorage before. Here is 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);
            }
    // ...

}

Compound ngx-webstorage was downloaded in npmjs

    
23.07.2018 / 18:48