Currently, I am attempting to utilize Ionic storage for the purpose of saving and loading an authentication token that is necessary for accessing the backend API in my application. However, I am encountering difficulties retrieving the value from storage.
Following the instructions on the component GH page: https://github.com/ionic-team/ionic-storage, I have successfully installed ionic storage (Angular version) using the command below:
npm install @ionic/storage-angular
Subsequently, I imported the storage service into my Globals service, which I established as a centralized repository for all global values within 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();
}
(...)
Furthermore, I designed a saveToken function that aims to store the authentication token, already specified within _authenticationToken
through 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(value => console.log("token saved."));
}
Upon executing the saveToken
function, the outcome is as follows (Disregard the red lines, they pertain to other processes as saveToken operates asynchronously):
https://i.sstatic.net/C3LzI.png
Consequently, the token was successfully saved, with its value visible within the Application Tab in Chrome Dev Tools:
https://i.sstatic.net/t5IK0.png
However, an issue arises when I attempt to retrieve the saved token utilizing the subsequent method, yielding a null value as if the token had not been saved. This action is intended for reinstating the login session when the application is reopened:
public loadToken(): Promise<void>
{
return this.storage.get("AuthenticationToken")
.then(val => {
console.log("token loaded");
console.log(val);
this.setToken(val);
});
}
The aforementioned code leads to the following messages, indicating a failure to retrieve any value from storage:
https://i.sstatic.net/yfxTI.png
While operating the application on the Chrome browser using ionic serve
, I initially suspected that the storage might be resetting upon app reloads. Nevertheless, after inspecting the Application Tab, I confirmed that the Authentication Token remains intact.