I'm trying to use ionic storage to save and load an authentication token I use to access the backend API in my APP, but I'm having trouble getting the value from storage.
I've installed ionic storage (Angular version), as indicated in the component GH page: https://github.com/ionic-team/ionic-storage, using the command below:
npm install @ionic/storage-angular
Then I imported the storage service in my Globals service, which I created to be a hub to all global values in my application:
import { Storage } from '@ionic/storage-angular';
@Injectable()
export class Globals {
private _authenticationToken: string;
constructor(private storage: Storage) {
this._authenticationToken = null;
this.storage.create();
}
(...)
Then I created a saveToken method, that will store the authentication token, already defined in _authenticationToken by another method, in the ionic storage:
public saveToken() : Promise<void>
{
console.log("Saving token");
console.log(this._authenticationToken);
return this.storage.set("AuthenticationToken", this._authenticationToken)
.then(valor => console.log("token saved."));
}
When I execute the saveToken method, the result is this (Ignore the lines in red, they are from other process, since saveToken is async):
So my token was saved, and I can see its value in Application Tab in Chrome Dev Tools:
But here comes the problem. When I try to load the saved token, using the method bellow, I get a null value returned, as if the token was not saved. I'm doing that when the application is opened again, to recover the login session.
public loadToken() : Promise<void>
{
return this.storage.get("AuthenticationToken")
.then(v => {
console.log("token loaded");
console.log(v);
this.setToken(v);
});
}
The code above will result in the following messages, indicating that no value was returned from storage.
I'm running the application in chrome browser, using ionic serve, and thought that the storage could be resetting after the app reloads, but I've checked the application tab and the Authentication Token is there.



Before I share the possible solution and then I explain:
That's one way using a callback to get the result without moving your internal logic.
The reason you are not getting anything is because you are trying to return an asynchronous result (promise) and then(); it will always return null to you. Your result is inside the then.
Another way would be this (but you will have to migrate the logic inside from where you consume it):
Best regards.