Search code examples
angularionic2local-storage

ionic2 local storage get


I just started to use ionic2, where in my app I ask the user to store an apiKey and secret.

When storing in local storage it works fine, but I am getting trouble when try to use stored value.

// Storing user apikey config
saveAPISettings(apiConfig) {
  let apiSettings = { apiKey: apiConfig.apiKey, apiKeySecret: apiConfig.apiKeySecret};
  this.storage.set('api-settings', JSON.stringify(apiSettings));
}

// Stored value
"api-settings": "{"apiKey":"2b749127b41927b491274b924927b412","apiKeySecret":"QEWIRP"}" 


// Getting stored apikey config
getSettings(key) {
  let results = [];
  let object;

  this.storage.get(key).then((val) => {
    object = JSON.parse(val);
    results['apiKey'] = object.apiKey;
    results['apiKeySecret'] = object.apiKeySecret;
  });
  return results;
}

enter image description here

 // getSettings usage
 let config = getSettings('api-settings');

 // getting undefined
 console.log(config.apiKey);
 or 
 console.log(config['apiKey']);

What am I doing wrong here?


Solution

  • No need to stringify your object apiSettings just save as object

    this.storage.set('api-settings', apiSettings);
    

    Storage.get will resolve a promise just return the storage in getSettings

    getSettings(key) {
      return this.storage.get(key)
    }
    

    In your settings page

     getSettings('api-settings').then(val=>{
       console.log(val.apiKey);
       console.log(val.apiKeySecret);
    });