Angular storage get return undefined

Hi, I´m developing an Ionic / Angular APP and for save and get token´s user I’m using storage The problem is that I am facing problem when trying to get the token, In fact I have to try two or more times to finally receive the token.

On the home screen I simulate a login with the data I need:

import { Storage } from '@ionic/storage';
    
private _Storage: Storage

this._Storage.set('X-Access-Token', 'f27bf5399b81c701bd9d6158ca67bb58');
this._Storage.set('isLogged', 'true');
this._Router.navigate(['/dashboard']);

To be able to retrieve the X-Access-Token in the compoment dashboard (and all other components) I have to call the GetAccessToken function with ngOnInit, and then inside the main function of each component.

    XAccessToken: any;

    ngOnInit() { 
       this.GetXAccessToken();
    }
    
     GetXAccessToken() {
        this._Storage.get('X-Access-Token').then((token) => {
          this.XAccessToken = token;
        });
      }
    
    ionViewDidEnter() {
        this.GetChannelsFollowed();  
      }
    
      async GetChannelsFollowed() {
        this.GetXAccessToken();
     ....
     }

My recommendation is to never use Storage to communicate within a run of the app. Only use it to communicate with the future: write whenever you wish, but read only once at app startup. If you follow this rule, you will magically design away your problem. For in-app communication, use a Promise or Observable exposed by a service, which in turn can read from storage at the time of its creation.

Hi, thanks for your feedback. I wil get the doc, ready and start using the Observable on this project. Do you think is better save the data using storage only the check in future to keep the user connected?

I’m not entirely sure I understand you here, so let me try rephrasing and ask you if this is what you mean:

Do you recommend storing access tokens using Ionic Storage so that the the app can automatically reauthenticate the user the next time the app is launched in the future?

If that’s the question, then yes, I think that’s a perfectly reasonable thing to do.

This is the question… Thanks… :slight_smile: I am starting reading it now and I will share the result.