Storage isn't keeping data


#1

Hi there,

i have a problem with Storage, i have this provider:

import { Injectable } from '@angular/core';
import { JwtHelper, tokenNotExpired } from 'angular2-jwt';
import { Storage } from '@ionic/storage';
import 'rxjs/add/operator/map';

@Injectable()
export class Storejwt {
    private jwtHelper: JwtHelper;

    constructor(private local: Storage) {
        this.jwtHelper = new JwtHelper();
    }

    /**
     * Obtener Dato por Clave desde el Storage
     */
    public getDato(clave: string): any {
        return this.local.get(clave);
    }

    /**
     * Asignar dato a una Clave en el Storage
     */
    public setDato(clave: string, valor: any): any {
        return this.local.set(clave, valor);
    }

    /**
     * Remover Dato por Clave del Storage
     */
    public delDato(clave: string): any {
        return this.local.remove(clave);
    }

    /**
     * Decodificar token en formato JWT
     */
    public decodeToken(token: any): any {
        let rtnData: any = null;

        try {
            rtnData = this.jwtHelper.decodeToken(token);
        } catch (e) {
            console.error('Storejwt Error (decodeToken): ' + e)
        }

        return rtnData;
    }

    /**
     * Verificar si el token a expirado o no (True: aún no ha expirado, False: ya expiró)
     */
    public isActive(token: any) {
        let tk_expired = false;
        try {
            tk_expired = tokenNotExpired(null, token);
        } catch (e) {
            console.error('Storejwt Error (isActive): ' + e)
        }
        return tk_expired;
    }

}

yes, it is in app.module.ts (into providers), and when i login i do this:

this._storeJwt.setDato('id_token', data);

yes, it’s imported and injected in constructor. But when i change page, id_token data is lost for example, i call this function:

let token = this._storeJwt.getDato('id_token');

and it’s null :confused:

What i have done bad?, thanks in advance.

PD: I did npm install @ionic/storage --save, and cordova-sqlite-storage (yes, the cordova plugins is innecesary for my case, but…)


#2

I assume you’re testing on device, since you’re mentioning cordova-sqlite-storage.

I ran into a similar issue. Turns out somewhere I was attempting to write to storage before platform was ready. Make sure to wrap calls to ionic-storage in platform ready calls.

this.platform.ready().then(() => {
  this.local.set('key', 'val');
});

#3

Storage return a promise, you must also use promise on your providers


#4

^ This.

Didn’t notice how @bssanchez was retrieving the token.


#5

Yes, thanks so much…

i change my get function to:

/**
 * Obtener Dato por Clave desde el Storage
 */
public getDato(clave: string): any {
    return new Promise((valor) => {
        this.local.get(clave).then((_valor) => {
            valor(_valor);
        });
    });
}

and it’s works :smiley:


#6

It looks to me like you have fallen into the explicit promise constructor antipattern pit.